<?php
// +----------------------------------------------------------------------
// | quanli team
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2020 http://www.fistforward.com/ All rights reserved.
// +----------------------------------------------------------------------
// | Author: allen.qiang
// +----------------------------------------------------------------------

/**
 * 微信操作类
 * @package  htdocs
 * @subpackage  quanliadmin
 * @author   allen.qiang
 * @version 1.0
 */

class wechatHandler {

    private $dbca;

    public function __construct( $dbca ) {
        $this->dbca = $dbca;
    }

    // 全角半角转换函数
    function banjiao($str) {

        if( !isset($str) || empty($str) ){
            return NULL;
        }

        $arr = array(
            //数字
            '０' => '0', '１' => '1', '２' => '2', '３' => '3', '４' => '4', '５' => '5', '６' => '6', '７' => '7', '８' => '8', '９' => '9',
            //大写字母
            'Ａ' => 'A', 'Ｂ' => 'B', 'Ｃ' => 'C', 'Ｄ' => 'D', 'Ｅ' => 'E', 'Ｆ' => 'F', 'Ｇ' => 'G', 'Ｈ' => 'H', 'Ｉ' => 'I', 'Ｊ' => 'J', 'Ｋ' => 'K', 'Ｌ' => 'L', 'Ｍ' => 'M', 'Ｎ' => 'N', 'Ｏ' => 'O', 'Ｐ' => 'P', 'Ｑ' => 'Q', 'Ｒ' => 'R', 'Ｓ' => 'S', 'Ｔ' => 'T', 'Ｕ' => 'U', 'Ｖ' => 'V', 'Ｗ' => 'W', 'Ｘ' => 'X', 'Ｙ' => 'Y', 'Ｚ' => 'Z',
            // 小写字母
            'ａ' => 'a', 'ｂ' => 'b', 'ｃ' => 'c', 'ｄ' => 'd', 'ｅ' => 'e', 'ｆ' => 'f', 'ｇ' => 'g', 'ｈ' => 'h', 'ｉ' => 'i', 'ｊ' => 'j', 'ｋ' => 'k', 'ｌ' => 'l', 'ｍ' => 'm', 'ｎ' => 'n', 'ｏ' => 'o', 'ｐ' => 'p', 'ｑ' => 'q', 'ｒ' => 'r', 'ｓ' => 's', 'ｔ' => 't', 'ｕ' => 'u', 'ｖ' => 'v', 'ｗ' => 'w', 'ｘ' => 'x', 'ｙ' => 'y', 'ｚ' => 'z',
            //括号
            '（' => '(', '）' => ')', '〔' => '[', '〕' => ']', '【' => '[', '】' => ']', '〖' => '[', '〗' => ']', '《' => ' < ','》' => ' > ','｛' => ' {', '｝' => '} ',
            //其它
            '％' => '%', '＋' => ' + ', '—' => '-', '－' => '-', '～' => '-','．'=>'.','：' => ':', '。' => '.', '，' => ',', '、' => '\\', '；' => ':', '？' => '?', '！' => '!', '…' => '-', '‖' => '|','“' => "\"", '”' => "\"", '‘' => '`','’' => '`', '｜' => '|', '〃' => "\"",'　' => ' '
        );

        return strtr($str, $arr);
    }

    /**
     * 查询关键词
     * @param array $arg_array 查询参数数组
     * $arg_array = array (
     *      'sortname' => string 排序字段
     *      'sortorder' => string 排序方式
     *      'page' => int 分页页码
     *      'rp' => int 分页页数
     * )
     * @return null
     */
    public function searchKeyWords( &$arg_array ) {

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //关键词
        if ( isset($arg_array['keyword']) && !empty($arg_array['keyword']) ) {
            $sql .= ' AND keyword = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['keyword'];
        }

        if ( isset($arg_array['keyID']) && !empty($arg_array['keyID']) ) {
            $sql .= ' AND keyID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['keyID'];
        }

        //使用标志
        if ( isset($arg_array['useFlg']) && in_array($arg_array['useFlg'], array('0', '1')) ) {
            $sql .= ' AND useFlg = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['useFlg'];
        }

        //父级关键词
        if ( isset($arg_array['parentID']) ) {
            $sql .= ' AND parentID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['parentID'];
        }

        if ( $sql ) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if ( isset($arg_array['rp']) && $arg_array['rp'] > 1 ) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM wechat_keywords ' . $sql;

                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if ( isset($arg_array['sortname']) && !empty($arg_array['sortname']) )
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if ( !isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0 )
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if ( isset($arg_array['sortname']) && !empty($arg_array['sortname']) )
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询分类信息
            $search_sql = 'SELECT * FROM wechat_keywords ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            foreach($temp_item_array as &$item) {

                $item_array[] = array(
                    'keyID' 	  => $item->keyID,
                    'keyword' 	  => $item->keyword,
                    'keyType' 	  => $item->keyType,
                    'description' => $item->description,
                    'useFlg'      => $item->useFlg,
                    'useName' 	  => $item->useFlg ? '启用' : '禁用',
                    'replyID' 	  => $item->replyID,
                    'parentID' 	  => $item->parentID,
                    'level' 	  => $item->level,
                    'isNeedReply' 	=> $item->isNeedReply,
                    'replyType' 	=> $item->replyType
                );

            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }

    /**
     * 查询微信回复内容设置
     * @param array $arg_array 查询参数数组
     * $arg_array = array (
     *      'sortname' => string 排序字段
     *      'sortorder' => string 排序方式
     *      'page' => int 分页页码
     *      'rp' => int 分页页数
     * )
     * @return null
     */
    public function searchAutoReply( &$arg_array ) {

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //回复内容ID
        if (isset($arg_array['replyID']) && is_numeric($arg_array['replyID'])) {
            $sql .= ' AND replyID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['replyID'];
        }

        //replayID字符串
        if (isset($arg_array['replyID_str']) && is_numeric($arg_array['replyID_str'])) {
            $sql .= ' AND replyID IN (?)';
            $params_type .= 's';
            $params_array[] = $arg_array['replyID_str'];
        }

        //回复标题
        if (isset($arg_array['replyTitle']) && !empty($arg_array['replyTitle'])) {
            $sql .= ' AND replyTitle LIKE ?';
            $params_type .= 's';
            $params_array[] = '%' . $arg_array['replyTitle'] . '%';
        }

        //使用标志
        if (isset($arg_array['useFlg']) && $arg_array['useFlg'] != 'all') {
            $sql .= ' AND useFlg = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['useFlg'];
        }

        //消息类型
        if (isset($arg_array['type']) && !empty($arg_array['type'])) {
            $sql .= ' AND type = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['type'];
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM wechat_autoReply ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询分类信息
            $search_sql = 'SELECT * FROM wechat_autoReply ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            foreach($temp_item_array as &$item) {

                $item_array[] = array(
                    'replyID' 	   => $item->replyID,
                    'replyTitle'   => $item->replyTitle,
                    'replyContent' => $item->replyContent,
                    'useFlg'       => $item->useFlg,
                    'type'         => $item->type,
                    'timeFlg' 	   => $item->timeFlg,
                    'startDate'    => !is_null($item->startDate) ? $item->startDate : '',
                    'endDate'      => $item->endDate,
                    'cycleDay'     => !is_null($item->cycleDay) ? $item->cycleDay : '',
                );

            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }


    /**
     * 查询微信消息记录表
     * @param array $arg_array 查询参数数组
     * $arg_array = array (
     *      'sortname' => string 排序字段
     *      'sortorder' => string 排序方式
     *      'page' => int 分页页码
     *      'rp' => int 分页页数
     * )
     * @return null
     */
    public function searchMsgLog( &$arg_array ) {

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //使用标志
        if (isset($arg_array['type']) && is_numeric($arg_array['type']) && in_array($arg_array['type'], array(1,2))) {
            $sql .= ' AND type = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['type'];
        }

        //创建时间
        if ( isset( $arg_array['startDate'], $arg_array['endDate'] ) && !empty( $arg_array['startDate'] ) && !empty( $arg_array['endDate'] ) ) {
            $sql .= ' AND createTime >= ? AND createTime <= ?';
            $params_type .= 'ss';
            $params_array[] = $arg_array['startDate'] . ' 00:00:00';
            $params_array[] = $arg_array['endDate'] . ' 23:59:59';
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM wechat_message_log ' . $sql;

                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询分类信息
            $search_sql = 'SELECT * FROM wechat_message_log ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            foreach($temp_item_array as &$item) {

                switch ($item->messageType){
                    case 1:
                        $messageTypeName = '文字';
                        break;
                    case 2:
                        $messageTypeName = '图片';
                        break;
                    case 3:
                        $messageTypeName = '图文';
                        break;
                    case 4:
                        $messageTypeName = '语音';
                        break;
                    case 6:
                        $messageTypeName = '地理位置';
                        break;
                    case 7:
                        $messageTypeName = '链接类消息';
                        break;
                    case 8:
                        $messageTypeName = '事件类消息';
                        break;
                    default:
                        $messageTypeName = '未知类型';
                        break;
                }

                $item_array[] = array(
                    'logId' => $item->logId,
                    'openId' => $item->openId,
                    'type' => $item->type,
                    'typeName' => ($item->type == 1) ? '推送消息' : '接收消息',
                    'messageId' => $item->messageId,
                    'message' => $item->message,
                    'replyID' => $item->replyID,
                    'messageType' => $item->messageType,
                    'messageTypeName' => $messageTypeName,
                    'reciveInfo' => $item->reciveInfo,
                    'pushInfo' => $item->pushInfo,
                    'pictureLink' => $item->pictureLink,
                    'linkUrl' => $item->linkUrl,
                    'linkTitle' => $item->linkTitle,
                    'linkDescription' => $item->linkDescription,
                    'location_x' => $item->location_x,
                    'location_y' => $item->location_y,
                    'location_scale' => $item->location_scale,
                    'location_Label' => $item->location_Label,
                    'eventType' => $item->eventType,
                    'eventKey' => $item->eventKey,
                    'messageTime' => $item->messageTime
                );

            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }

    /**
     * 查询微信会员列表
     *
     * @param array $arg_array 查询参数数组
     *
     * $arg_array = array (
     *      'sortname'  => string 排序字段
     *      'sortorder' => string 排序方式
     *      'page'      => int 分页页码
     *      'rp'        => int 分页页数
     * )
     *
     * @return null
     */
    public function searchUserList( &$arg_array ) {

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //会员编号
        if( isset( $arg_array['pcustID'] ) && !empty( $arg_array['pcustID'] ) ){
            $sql .= ' AND pcustID = ?';
            $params_type .= 'i';
            $params_array[] = trim( $arg_array['pcustID'] );
        }

        //uuid
        if( isset( $arg_array['uuid'] ) && !empty( $arg_array['uuid'] ) ){
            $sql .= ' AND uuid = ?';
            $params_type .= 's';
            $params_array[] = trim( $arg_array['uuid'] );
        }

        //openId
        if( isset( $arg_array['openId'] ) && !empty( $arg_array['openId'] ) ){
            $sql .= ' AND openId = ?';
            $params_type .= 's';
            $params_array[] = trim( $arg_array['openId'] );
        }

        //总(门)店号
        if( isset( $arg_array['totalStores'] ) && !empty( $arg_array['totalStores'] ) ){
            $sql .= ' AND extend_1 LIKE ?';
            $params_type .= 's';
            $params_array[] = '%' . trim( $arg_array['totalStores'] ) . '%';
        }

        //会员卡号
        if( isset( $arg_array['memberID'] ) && !empty( $arg_array['memberID'] ) ){
            $sql .= ' AND extend_5 = ?';
            $params_type .= 's';
            $params_array[] = trim( $arg_array['memberID'] );
        }

        //会员名(微信号)
        if( isset( $arg_array['userName'] ) && !empty( $arg_array['userName'] ) ){
            $sql .= ' AND userName = ?';
            $params_type .= 's';
            $params_array[] = trim( $arg_array['userName'] );
        }

        //微信会员名
        if( isset( $arg_array['nickName'] ) && !empty( $arg_array['nickName'] ) ){
            $sql .= ' AND nickName = ?';
            $params_type .= 's';
            $params_array[] = trim( $arg_array['nickName'] );
        }

        //关注状态
        if( isset( $arg_array['useFlg'] ) && in_array($arg_array['useFlg'], array(1, 2) ) ){
            $sql .= ' AND extend_7 = ?';
            $params_type .= 'i';

            if($arg_array['useFlg'] == 1){
                $params_array[] = 0;
            }else{
                $params_array[] = 1;
            }
        }

        //注册时间
        if ( isset( $arg_array['startDate'], $arg_array['endDate'] ) && !empty( $arg_array['startDate'] ) && !empty( $arg_array['endDate'] ) ) {
            $sql .= ' AND createTime >= ? AND createTime <= ?';
            $params_type .= 'ss';
            $params_array[] = $arg_array['startDate'] . ' 00:00:00';
            $params_array[] = $arg_array['endDate'] . ' 23:59:59';
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if ( isset( $arg_array['rp'] ) && $arg_array['rp'] > 1 ) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM wechat_customer ' . $sql;
                $count_array = &$this->dbca->stmt_query( $search_sql, $params_type, $params_array );
                $item_count = $count_array[0]->item_count;
                if ( $item_count == 0 ) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if ( isset( $arg_array['sortname'] ) && !empty( $arg_array['sortname'] ) )
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if ( !isset( $arg_array['page'] ) || !is_numeric( $arg_array['page'] ) || $arg_array['page'] <= 0 )
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);


            } else {

                //排序
                if ( isset( $arg_array['sortname'] ) && !empty( $arg_array['sortname'] ) )
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询微信会员信息
            $search_sql = 'SELECT * FROM wechat_customer ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if ( !$temp_item_array )
                return null;

            foreach( $temp_item_array as &$item ) {

                //查询微信会员分组信息
                $group_array = array(
                    'groupID' => $item->groupID
                );

                $user_group = $this->searchUserGroupList($group_array);
                if($user_group){
                    $item->groupName = $user_group[0]['groupName'];
                }else{
                    $item->groupName = null;
                }

                $item_array[] = array(
                    'openId' 		 => $item->openId,
                    'extend_1' 		 => $item->extend_1,
                    'pcustID' 		 => $item->pcustID,
                    'extend_5' 		 => $item->extend_5,
                    'fakeId'		 => $item->fakeId,
                    'userName' 		 => $item->userName,
                    'nickName' 		 => $item->nickName,
                    'isVerification' => $item->isVerification,
                    'sex'            => $item->sex,
                    'groupName'		 => $item->groupName,
                    'remarkName' 	 => $item->remarkName,
                    'country' 	 	 => $item->country,
                    'province' 	 	 => $item->province,
                    'city' 		 	 => $item->city,
                    'createTime'  	 => $item->createTime,

                );

            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }

    /**
     * 查询实时消息列表
     *
     * @param array $arg_array 查询参数数组
     *
     * $arg_array = array (
     *      'sortname'  => string 排序字段
     *      'sortorder' => string 排序方式
     *      'page'      => int 分页页码
     *      'rp'        => int 分页页数
     * )
     *
     * @return null
     */
    public function searchNewsList( &$arg_array ) {

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //消息时限
        if( isset( $arg_array['timeFlg'] ) && !empty( $arg_array['timeFlg'] ) ){
            switch ($arg_array['timeFlg']){
                case 1:	//今天
                    $sql .= ' AND wl.createTime >= ? AND wl.createTime <= ?';
                    $params_type .= 'ss';
                    $params_array[] = date('Y-m-d') . ' 00:00:00';
                    $params_array[] = date('Y-m-d') . ' 23:59:59';

                    break;
                case 2:	//昨天
                    $sql .= ' AND wl.createTime >= ? AND wl.createTime <= ?';
                    $params_type .= 'ss';
                    $params_array[] = date('Y-m-d', strtotime('1 days ago')) . ' 00:00:00';
                    $params_array[] = date('Y-m-d', strtotime('1 days ago')) . ' 23:59:59';
                    break;
                case 3:	//更早
                    $sql .= ' AND wl.createTime < ?';
                    $params_type .= 's';
                    $params_array[] = date('Y-m-d', strtotime('1 days ago')) . ' 00:00:00';
                    break;
            }
        } else {
            $sql .= ' AND wl.createTime >= ? AND wl.createTime <= ?';
            $params_type .= 'ss';
            $params_array[] = date('Y-m-d', strtotime('1 days ago')) . ' 00:00:00';
            $params_array[] = date('Y-m-d', strtotime('1 days ago')) . ' 23:59:59';
        }

        //消息类型
        if( isset( $arg_array['type'] ) && in_array( $arg_array['type'], array(1, 2) ) ){
            $sql .= ' AND wl.type = ?';
            $params_type .= 'i';
            $params_array[] = trim( $arg_array['type'] );
        }

        //会员编号(替换oenpId)
        if( isset( $arg_array['pcustID'] ) && !empty( $arg_array['pcustID'] ) ){
            $sql .= ' AND wr.pcustID = ?';
            $params_type .= 's';
            $params_array[] = trim( $arg_array['pcustID'] );
        }

        //创建时间
        if ( isset( $arg_array['startDate'], $arg_array['endDate'] ) && !empty( $arg_array['startDate'] ) && !empty( $arg_array['endDate'] ) ) {
            $sql .= ' AND wl.createTime >= ? AND wl.createTime <= ?';
            $params_type .= 'ss';
            $params_array[] = $arg_array['startDate'] . ' 00:00:00';
            $params_array[] = $arg_array['endDate'] . ' 23:59:59';
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if ( isset( $arg_array['rp'] ) ) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM wechat_message_log wl
							   INNER JOIN wechat_user_record wr ON wl.openId = wr.openId ' . $sql;
                $count_array = &$this->dbca->stmt_query( $search_sql, $params_type, $params_array );
                $item_count = $count_array[0]->item_count;
                if ( $item_count == 0 ) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if ( isset( $arg_array['sortname'] ) && !empty( $arg_array['sortname'] ) )
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if ( !isset( $arg_array['page'] ) || !is_numeric( $arg_array['page'] ) || $arg_array['page'] <= 0 )
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);


            } else {

                //排序
                if ( isset( $arg_array['sortname'] ) && !empty( $arg_array['sortname'] ) )
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询微信消息记录
            $search_sql = 'SELECT wl.*,wr.pcustID,wr.userName,wr.nickName,wr.remarkName,wr.openId oid FROM wechat_message_log wl
						   INNER JOIN wechat_user_record wr ON wl.openId = wr.openId ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if ( !$temp_item_array ) {
                return null;
            }

            foreach( $temp_item_array as $key=>&$item ) {

                $item_array[] = array(
                    'openId'     => $item->oid,
                    'pcustID'	 => $item->pcustID,
                    'userName'   => $item->userName,
                    'nickName'   => $item->nickName,
                    'remarkName' => $item->remarkName,
                    'createTime' => $item->createTime,
                    'type' 		 => $item->type,
                    'message'    => $item->message
                );
            }

            return isset($item_array) ? $item_array : null;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }

    /**
     * 查询微信会员分组列表
     *
     * @param array $arg_array 查询参数数组
     *
     * $arg_array = array (
     *      'sortname'  => string 排序字段
     *      'sortorder' => string 排序方式
     *      'page'      => int 分页页码
     *      'rp'        => int 分页页数
     * )
     *
     * @return null
     */
    public function searchUserGroupList( &$arg_array ) {

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //分组编号
        if( isset( $arg_array['groupID'] ) && !empty( $arg_array['groupID'] ) ){
            $sql .= ' AND groupID = ?';
            $params_type .= 'i';
            $params_array[] = trim( $arg_array['groupID'] );
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if ( isset( $arg_array['rp'] ) && $arg_array['rp'] > 1 ) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM wechat_customer_group ' . $sql;
                $count_array = &$this->dbca->stmt_query( $search_sql, $params_type, $params_array );
                $item_count = $count_array[0]->item_count;
                if ( $item_count == 0 ) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if ( isset( $arg_array['sortname'] ) && !empty( $arg_array['sortname'] ) )
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if ( !isset( $arg_array['page'] ) || !is_numeric( $arg_array['page'] ) || $arg_array['page'] <= 0 )
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);


            } else {

                //排序
                if ( isset( $arg_array['sortname'] ) && !empty( $arg_array['sortname'] ) )
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询微信会员信息
            $search_sql = 'SELECT * FROM wechat_customer_group ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if ( !$temp_item_array )
                return null;

            foreach( $temp_item_array as &$item ) {

                $item_array[] = array(
                    'groupID'   => $item->groupID,
                    'groupName' => $item->groupName,
                    'useFlg'    => $item->useFlg,
                );

            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }

    /**
     * 保存回复内容信息
     *
     * @param array $arg_array 保存参数数组
     *
     * $arg_array = array (
     *      'wechat_type' => int 回复类型
     *      'replyTitle'  => string 回复标题
     *      'useFlg'      => int 使用状态
     *      'replyID'     => int 回复内容ID
     *      未完......
     * )
     *
     * @return null
     */
    public function saveAutoReply( &$arg_array ){

        if ( !isset($arg_array['wechat_type'], $arg_array['replyTitle'], $arg_array['useFlg'], $arg_array['replyID']) ) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }

        //根据消息类型，校验数据
        if ( empty($arg_array['wechat_type']) || !in_array($arg_array['wechat_type'],array(1, 2, 3, 4)) ) {
            return array( 'code' => 400, 'message' => '消息类型有误，请核对后操作');
        }

        if ($arg_array['wechat_type'] == 1) {//文本消息
            if ( !isset( $arg_array['replyContent']) || empty($arg_array['replyContent'] ) ) {
                return array( 'code' => 400, 'message' => '消息内容不能为空' );
            }
        }elseif ($arg_array['wechat_type'] == 2){//图片消息

        }elseif ($arg_array['wechat_type'] == 3){//图文消息

            $picNum = $arg_array['picNum'];  //获取图片数量

            $material_id_arr = array();   //记录符合要求的素材
            $material_del_arr = array();  //要删除的素材
            $img_exists_arr = array();    //记录图片信息数组（全部  缺少：0  存在：1）
            for ($i=1;$i<=$picNum;$i++){
                if (!empty($arg_array['hidImg_'.$i])) {
                    if (empty($arg_array['title_'.$i]) || empty($arg_array['link_'.$i]) || empty($arg_array['description_'.$i])) {
                        return (array( 'code' => 400, 'message' => '图文信息不完整，请完善后操作'));
                    }else {
                        $material_id_arr[] = $i;
                    }
                }elseif ((!empty($arg_array['title_'.$i]) || !empty($arg_array['link_'.$i]) || !empty($arg_array['description_'.$i])) && (empty($arg_array['hidImg_'.$i]) && empty($arg_array['materialID_'.$i])) ){
                    error_log('校验结果：');
                    $img_exists_arr[] = 0;
                }
            }

            if (in_array(0,$img_exists_arr)) {
                return array( 'code' => 400, 'message' => '图片信息不能为空' );
            }
        }elseif ($arg_array['wechat_type'] == 4){//语音消息
            error_log('语音');
        }

        if (!isset($arg_array['timeFlg'])) {
            return array( 'code' => 400, 'message' => '时间标识不能为空' );
        }
        if (!in_array($arg_array['timeFlg'],array(0,1))) {
            return array( 'code' => 400, 'message' => '时间标识不符合要求' );
        }

        //有效时间校验
        $startDate	= isset($arg_array['startDate']) ? $arg_array['startDate'] : "";

        if ($arg_array['timeFlg'] == 1) {
            if (empty($startDate)) {
                return array( 'code' => 400, 'message' => '开始时间不能为空' );
            }

            if (!strstr($startDate,":")) {
                $startDate .= " 00:00:00";
            }

        }

        $wechat_autoReply = new entity('wechat_autoReply');

        //如果消息编号不为空则查询检查消息编号
        if($arg_array['replyID'] != 0){
            $wechat_autoReply->replyID = $arg_array['replyID'] ;
            if(!$this->dbca->fetch($wechat_autoReply)){
                return array( 'code' => 400, 'message' => sprintf('编号为「%d」,的消息不存在,请核对后操作',$arg_array['replyID']));
            }
            $materialReplyID = $arg_array['replyID'];
            $wechat_autoReply->editor = $arg_array['creator'] ;
        }else {
            $wechat_autoReply->creator = $arg_array['creator'] ;
        }

        //保存和更新回复内容信息
        $wechat_autoReply->replyTitle	= htmlspecialchars(trim($arg_array['replyTitle']));
        $wechat_autoReply->type			= trim($arg_array['wechat_type']);
        $wechat_autoReply->useFlg		= trim($arg_array['useFlg']);
        $wechat_autoReply->timeFlg		= $arg_array['timeFlg'];
        if ($arg_array['timeFlg'] == 1) {
            $wechat_autoReply->startDate	= $startDate;
            $wechat_autoReply->cycleDay		= $arg_array['cycleDay'];  //有效期天数

            //分解日期格式(例如：2013-07-04 00:00:00)
            $getDay = explode(' ' , $startDate);

            //获取日期（例如：2013-07-04）
            $day = $getDay[0];

            //获取开始时间的时间戳
            $timeStamp = strtotime( $day );

            //一天的秒数
            $secondDay = 86400;

            /**
             * 获取有效期结束时间的时间戳
             * 换算时，应该要将传入的有效期天数减一，比如有效期是三天，开始时间是2013-07-04
             * 那么，有效期为：2013-07-04  至  2013-07-06
             */
            $endtimeStamp = $timeStamp + ($arg_array['cycleDay']-1) * $secondDay;

            //将结束日期的时间戳转换成对应的日期
            $endDate = date('Y-m-d' , $endtimeStamp);

            //获取紧接着的一天
            $nextDateTimeStamp =  $timeStamp + $arg_array['cycleDay'] * $secondDay;

            //将结束日期的时间戳转换成对应的日期
            $nextDate = date('Y-m-d' , $nextDateTimeStamp);

            $wechat_autoReply->endDate = $endDate . ' 23:59:59';
        }else{
            $nextDate = '';
        }

        if ($arg_array['wechat_type'] == 1) {
            $wechat_autoReply->replyContent = htmlspecialchars(trim($arg_array['replyContent']));
        }

        /********************** 检查回复内容标题是否重复 ***********************/
        //查询出回复内容标题为“$arg_array['replyTitle']”的所有信息
        $check_sql = 'SELECT * from wechat_autoReply WHERE replyTitle=?';
        $check_result = $this->dbca->stmt_query($check_sql,'s',trim($arg_array['replyTitle']) );

        //检查该"回复内容标题"是否已经存在
        if( $check_result ){
            if($arg_array['replyID'] != 0 && $check_result[0]->replyID != $arg_array['replyID'] ){
                return array('message'=>'回复内容标题重复' , 'code'=>400 );
            }elseif( $arg_array['replyID'] == 0 ){
                return array('message'=>'回复内容标题重复' , 'code'=>400 );
            }
        }

        try {
            $this->dbca->beginTransaction();

            $save_flg = $this->dbca->save( $wechat_autoReply ) ;

            //获取新插入的replyID
            $newReplyID = $this->dbca->insert_id;

            if (!isset($materialReplyID)) {
                $materialReplyID = $this->dbca->insert_id;
            }

            if ($arg_array['wechat_type'] == 3) {//图文
                foreach ($material_id_arr as $i){
                    $materialUrl = trim($arg_array['hidImg_'.$i]);

                    $wechat_material = new entity('wechat_material');

                    if (!empty($arg_array['materialID_'.$i])) {

                        $wechat_material->materialID = $arg_array['materialID_'.$i];

                        if (!$this->dbca->fetch($wechat_material)) {
                            return array( 'code' => 400, 'message' => sprintf('编号为「%d」,的图文素材不存在,请核对后操作',$arg_array['materialID_'.$i]));
                        }
                        $wechat_material->editor = $arg_array['creator'];
                        if ($wechat_material->materialLink != $materialUrl) {
                            $wechat_material->materialLink = $this->uploadMaterial($materialUrl, 1);
                        }
                    }else {
                        $wechat_material->creator = $arg_array['creator'];
                        $wechat_material->materialLink = $this->uploadMaterial($materialUrl,1);
                    }
                    $wechat_material->title	= trim($arg_array['title_'.$i]);
                    $wechat_material->link	= trim($arg_array['link_'.$i]);
                    $wechat_material->description = trim($arg_array['description_'.$i]);
                    $wechat_material->sortOrder = $i;
                    $wechat_material->replyID = $materialReplyID;
                    $wechat_material->useFlg = trim($arg_array['useFlg']);
                    $this->dbca->save($wechat_material,'wechat');
                }

                //删除素材
                if (isset($arg_array['delArr']) && (count($arg_array['delArr']) != 0)) {
                    $material_str = implode(',',$arg_array['delArr']);
                    $del_sql = 'DELETE FROM wechat_material WHERE materialID in('. $material_str .')';
                    $this->dbca->stmt_query($del_sql);
                }
            }elseif ($arg_array['wechat_type'] == 4){//语音
                error_log('语音保存');
            }

            $this->dbca->commit();

            //组装返回数组
            $returnArr['replyID'] = $newReplyID;
            $returnArr['replyTitle'] = $arg_array['replyTitle'];
            $returnArr['replyContent'] = $arg_array['replyContent'];

            if ($arg_array['timeFlg'] == 1) {
                $returnArr['startDate'] = $arg_array['startDate']. ' 00:00:00';
                $returnArr['cycleDay'] = $arg_array['cycleDay'];
            }else{
                $returnArr['startDate'] = '';
                $returnArr['cycleDay']  = '';
            }

            return (array( 'code' => 200, 'message' => '微信回复内容消息保存成功' , 'data'=>array( $returnArr ) , 'nextDate'=>$nextDate , 'timeFlg'=>$arg_array['timeFlg'] ) );

        }catch (Exception $e){
            $this->dbca->rollBack();
            error_log($e->getMessage());

            return array( 'code' => 500, 'message' => '微信回复内容消息保存失败' );
        }
    }

    /**
     * 素材上传函数
     * @param string	$materialName	素材名称
     * @param int		$flg			标识		可选值 1：图片; 2：语音
     *
     */
    private function uploadMaterial($materialName,$flg){
        if (empty($materialName)) {
            return $materialName;
        }

        if (strstr($materialName,'quanliadmin/docroot/images')) {
            return $materialName;
        }

        if (!in_array($flg,array(1,2))) {
            return $materialName;
        }

        if ($flg == 1) {
            $subPath = 'image';
        }elseif ($flg == 2){
            $subPath = 'voice';
        }

        $dateDir  = $subPath. '/' .date('Ym');	//文件夹目录
        $savePath = G_APPLICATION_BASEPATH.'quanliadmin/docroot/images/wechat/';	//上传素材文件（源文件）

        //素材保存的目录（目标目录）
        $relative_path = 'quanliadmin/docroot/images/wechat/' . $dateDir .'/';
        $target_path = G_APPLICATION_BASEPATH.$relative_path;
        if(!file_exists($target_path))
            mkdir($target_path , 0777 , true);

        //防止页面刷新
        if(!file_exists($savePath . $materialName))
            return $relative_path.$materialName;

        if(file_exists($target_path.$materialName))
            @unlink($target_path.$materialName);


        //将图片移动到指定目录
        copy($savePath.$materialName , $target_path.$materialName);
        @unlink($savePath.$materialName);

        return '/'.$relative_path.$materialName;

    }

    /**
     * 删除微信回复内容消息
     */
    public function deleteAutoReply( &$arg_array ){

        //消息编号串检查
        if (!isset($arg_array['delArr'])){
            return array( 'code' => 400, 'message' => '缺少参数' );
        }

        if (count($arg_array['delArr']) <= 0){
            return array( 'code' => 400, 'message' => '请选择要删除的消息' );
        }

        //将消息编号串截成数组
        $delete_array = $arg_array['delArr'];

        //循环删除消息编号
        try {
            $this->dbca->beginTransaction();
            foreach( $delete_array as &$u_l ) {
                if (!is_numeric( $u_l )){
                    return array( 'code' => 400, 'message' => '参数错误' );
                }

                //查询回复内容消息
                $wechat_autoReply = new entity('wechat_autoReply');
                $wechat_autoReply->replyID = $u_l;
                if ($this->dbca->fetch( $wechat_autoReply )) {
                    $this->dbca->delete( $wechat_autoReply );

                    //删除素材信息
                    if($wechat_autoReply->type == 3){
                        $this->dbca->stmt_query( 'DELETE FROM wechat_material WHERE replyID = ?', 'i', $u_l );
                    }
                }
            }

            $this->dbca->commit();

            return array( 'code' => 200, 'message' => '删除成功' );
        }catch (Exception $e){
            $this->dbca->rollBack();

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                return array( 'code' => 500, 'message' => '系统错误' );
            }
        }
    }

    /**
     * 回复内容消息使用状态
     *
     * @param unknown_type $arg_array
     */
    public function actionAutoReply( &$arg_array ) {

        //参数检查
        if (!isset($arg_array['useFlg_str']) || $arg_array['useFlg_str'] == '') {
            return array( 'code' => 400, 'message' => '缺少参数' );
        }

        $str_array = explode('_', $arg_array['useFlg_str']);

        //查询消息是否存在或已经被操作
        $wechat_autoReply = new entity('wechat_autoReply');
        $wechat_autoReply->replyID = $str_array[0] ;
        if (!$this->dbca->fetch( $wechat_autoReply )) {
            return array( 'code' => 400, 'message' => sprintf('编号「%d」的消息不存在,请核对后操作',$str_array[0]));
        }

        //检查消息状态是否已经被修改	
        if($wechat_autoReply->useFlg == $str_array[1] && $str_array[1] == 1) {
            return array( 'code' => 400, 'message' => sprintf('编号「%d」的消息已启用',$str_array[0]));
        }

        if($wechat_autoReply->useFlg == $str_array[1] && $str_array[1] == 0) {
            return array( 'code' => 400, 'message' => sprintf('编号「%d」的消息已禁用',$str_array[0]));
        }

        //保存和更新消息
        $wechat_autoReply->useFlg = $str_array[1] ;
        $this->dbca->save( $wechat_autoReply , 'wechat' );

        if($str_array[1] == 1){
            return array( 'code' => 200, 'message' => sprintf('编号「%d」的消息启用成功',$str_array[0]) );
        }else if ($str_array[1] == 0) {
            return array( 'code' => 200, 'message' => sprintf('编号「%d」的消息禁用成功',$str_array[0]) );
        }
    }

    /**
     * 查询文章分类
     * @param array $arg_array                          查询参数数组
     * $arg_array = array (
    'category_id' => int 文章分类ID
    'category_index' => int 文章分类索引
    'category_title' => int 文章分类标题
    'useFlg' => int 使用标志
    'sortname' => string 排序字段
    'sortorder' => string 排序方式
    'page' => int 分页页码
    'rp' => int 分页页数
     * )
     * @return null
     */
    public function searchArticleCategory( &$arg_array ) {

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //文章分类ID
        if (isset($arg_array['category_id']) && is_numeric($arg_array['category_id'])) {
            $sql .= ' AND category_id = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['category_id'];
        }

        //文章分类索引
        if (isset($arg_array['category_index']) && !empty($arg_array['category_index'])) {
            $sql .= ' AND category_index = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['category_index'];
        }

        //文章分类标题
        if (isset($arg_array['category_title']) && !empty($arg_array['category_title'])) {
            $sql .= ' AND category_title LIKE ?';
            $params_type .= 's';
            $params_array[] = '%' . $arg_array['category_title'] . '%';
        }

        //使用标志
        if (isset($arg_array['useFlg']) && is_numeric($arg_array['useFlg'])) {
            $sql .= ' AND useFlg = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['useFlg'];
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM wechat_content_article_category ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询分类信息
            $search_sql = 'SELECT * FROM wechat_content_article_category ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            foreach($temp_item_array as &$item) {
                $item_array[] = array(
                    'category_id' => $item->category_id,
                    'category_index' => $item->category_index,
                    'category_title' => $item->category_title,
                    'description' => $item->description,
                    'useFlg' => $item->useFlg
                );

            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }

    /**
     * 删除微信文章分类
     * @param $arg_array
     * @return array|null
     */
    public function deleteArticleCategory(&$arg_array){

        if(!isset($_REQUEST['delArr'])){
            return array('code'=>400,'message'=>'参数错误');
        }

        $delArr = $_REQUEST['delArr'];

        try{

            //循环删除
            foreach( $delArr as $key=>$delObj ){

                $del_sql = 'DELETE FROM wechat_content_article_category WHERE category_id = ? ' ;

                $this->dbca->stmt_query($del_sql,'i',$delObj);

            }

            return array('code'=>200,'message'=>'微信CMS分类及分类下的微信CMS删除成功');

        }catch( Exception $e ){
            error_log($e->getMessage());
            return null;

        }
    }

    /**
     * 添加或修改文章分类信息
     * @param array $arg_array 文章分类信息
     * @param array $arg_array['id']    分类ID
     * @param array $arg_array['index']    分类别名
     * @param array $arg_array['title']    分类标题
     * @param array $arg_array['useFlg']    使用标志
     * @param array $arg_array['description']    备注
     * @param array $arg_array['creator']    操作人ID
     * @return array
     */
    public function addArticleCategory( $arg_array ) {

        //检查是否缺少参数
        if (!isset($arg_array['id'], $arg_array['index'], $arg_array['title'], $arg_array['useFlg'], $arg_array['description']))
            return array( 'code' => 400, 'message' => '缺少参数' );

        //检查分类别名
        if (empty($arg_array['index']))
            return array( 'code' => 400, 'message' => '分类别名不能为空' );

        //检查分类标题
        if (empty($arg_array['title']))
            return array( 'code' => 400, 'message' => '分类标题不能为空' );

        //检查使用标志
        if (!in_array($arg_array['useFlg'], array(0, 1)))
            return array( 'code' => 400, 'message' => '请选择是否使用标志' );
        $commHandler = new commHandler();
        $arg_array['description'] = $commHandler->convertVar($arg_array['description']);

        try {

            $article_obj = new entity('wechat_content_article_category');
            if ($arg_array['id'] > 0) {
                $article_obj->category_id = $arg_array['id'];
                if (!$this->dbca->fetch($article_obj))
                    return array( 'code' => 404, 'message' => '分类信息没有找到' );
                $article_obj->editor = $arg_array['creator'];
            } else {
                $article_obj->creator = $arg_array['creator'];
            }
            $article_obj->category_index = $arg_array['index'];
            $article_obj->category_title = $arg_array['title'];
            $article_obj->description = $arg_array['description'];
            $article_obj->useFlg = $arg_array['useFlg'];
            $this->dbca->save($article_obj, 'content');

            if ( $arg_array['id'] == 0 )
                return array( 'code' => 200, 'message' => '保存成功' );
            else
                return array( 'code' => 200, 'message' => '修改成功' );

        } catch (Exception $e) {

            error_log($e->getMessage());
            return array( 'code' => 500, 'message' => '系统错误' );

        }


    }

    /**
     * 文章分类禁用启用
     * @param $arg_array
     * @return array|null
     */
    public function useArticleCategory( &$arg_array ){
        if(!isset($arg_array['category_id']) || !isset($arg_array['flg'])){
            return array('code'=>400,'message'=>'参数错误');
        }

        try{

            $article_category = new entity('wechat_content_article_category');
            $article_category->category_id = $arg_array['category_id'];
            if($this->dbca->fetch($article_category)){

                $article_category->useFlg = $arg_array['flg'];

                $this->dbca->save($article_category);

            }else{
                return array('code'=>400,'message'=>'不存在该分类');
            }

            if($arg_array['flg'] == 1){
                return array('code'=>200,'message'=>'微信CMS分类启用成功');
            }else{
                return array('code'=>200,'message'=>'微信CMS分类禁用成功');
            }

        }catch(Exception $e){
            error_log($e->getMessage());
            return null;
        }
    }

    /**
     * 查询文章
     * @param array $arg_array                          查询参数数组
     * $arg_array = array (
    'article_category_id' => int 分类ID
    'article_id' => int 文章ID
    'article_title' => string 文章标题
    'useFlg' => int 使用标志
    'sortname' => string 排序字段
    'sortorder' => string 排序方式
    'page' => int 分页页码
    'rp' => int 分页页数
     * )
     * @return null
     */
    public function searchArticle( &$arg_array ) {

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();


        //分类ID
        if (isset($arg_array['article_category_id']) && is_numeric($arg_array['article_category_id'])) {
            $sql .= ' AND article_category_id = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['article_category_id'];
        }

        //文章ID
        if (isset($arg_array['article_id']) && is_numeric($arg_array['article_id'])) {
            $sql .= ' AND article_id = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['article_id'];
        }

        //文章标题
        if (isset($arg_array['article_title']) && !empty($arg_array['article_title'])) {
            $sql .= ' AND article_title LIKE ?';
            $params_type .= 's';
            $params_array[] = '%' . $arg_array['article_title'] . '%';
        }

        //使用标志
        if (isset($arg_array['useFlg']) && is_numeric($arg_array['useFlg'])) {
            $sql .= ' AND useFlg = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['useFlg'];
        }

        //创建时间

        if (isset($arg_array['startDate']) && !empty($arg_array['startDate'])) {
            $startDate = $arg_array['startDate'].' 00:00:00';
            $sql .= ' AND createTime >= ?';
            $params_type .= 's';
            $params_array[] = $startDate;
        }

        if (isset($arg_array['endDate']) && !empty($arg_array['endDate'])) {
            $endDate = $arg_array['endDate'].' 23:59:59';
            $sql .= ' AND createTime <= ?';
            $params_type .= 's';
            $params_array[] = $endDate;
        }

        //CMS内容类型
        if (isset($arg_array['content_type']) && is_numeric($arg_array['content_type'])) {
            $sql .= ' AND content_type = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['content_type'];
        }


        if (isset($arg_array['extend']) && !empty($arg_array['extend'])) {
            $sql .= $arg_array['extend'];
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM wechat_content_article ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询分类信息
            $search_sql = 'SELECT * FROM wechat_content_article ' . $sql;



            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            foreach($temp_item_array as &$item) {
                $item_array[] = array(
                    'article_id' => $item->article_id,
                    'article_title' => $item->article_title,
                    'useFlg' => $item->useFlg,
                    'article_summary' => $item->article_summary,
                    'description' => isset($arg_array['article_id']) ? $item->description : null,
                    'article_category_index' => $item->article_category_index,
                    'article_category_id' => $item->article_category_id,
                    'article_category_name' => $item->article_category_name,
                    'createTime' => $item->createTime,
                    'code_type' => $item->code_type,
                    'activeType' => $item->activeType,
                    'code_startDate' => $item->code_startDate,
                    'code_endDate' => $item->code_endDate,
                    'use_startDate' => $item->use_startDate,
                    'use_endDate' => $item->use_endDate,
                    'limit_num' => $item->limit_num,
                    'useType' => $item->useType,
                    'useTime' => $item->useTime,
                    'appointment_num' => $item->appointment_num,
                    'promotionID' => $item->promotionID,
                    'link' => $item->article_link ? $item->article_link : G_WEBSITE_DOMAINNAME . sprintf('/shop/article-%d.html', $item->article_id)
                );

            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }

    /**
     * 添加或修改文章信息
     *
     * @param array $arg_array 文章信息数组
     *
     */
    function saveArticleInfo ($arg_array) {

        //检查是否缺少参数
        if (!isset($arg_array['creator'], $arg_array['article_id'], $arg_array['article_title'], $arg_array['category_id'], $arg_array['article_summary'] , $arg_array['activeType']))
            return array( 'code' => 400, 'message' => '缺少参数' );

        //检查标题
        if (empty($arg_array['article_title']))
            return array( 'code' => 400, 'message' => '请填写标题' );

        //检查分类
        if (!is_numeric($arg_array['category_id']) || $arg_array['category_id'] <= 0)
            return array( 'code' => 400, 'message' => '请选择分类' );

        //检查文章ID
        if (empty($arg_array['article_id']) || !is_numeric($arg_array['article_id']) || $arg_array['article_id'] < 0)
            $arg_array['article_id'] = 0;

        if( !isset($arg_array['activeType']) && !is_numeric( $arg_array['activeType'] , array(1,2,3) ) ){
            return array( 'code' => 400, 'message' => '活动类型有误' );
        }

        //CMS内容
        if($arg_array['description'] == ''){
            return array('code'=>400,'message'=>'正文不能为空');
        }

        //实例化公共类
        $commHandler = new commHandler();

        $arg_array['article_title'] = $commHandler->convertVar($arg_array['article_title']);
        $arg_array['article_summary'] = $commHandler->convertVar($arg_array['article_summary']);
        $arg_array['description'] = $commHandler->convertVar($arg_array['description']);

        try {

            //查询文章分类信息
            $c_arg_array = array(
                'category_id' => $arg_array['category_id']
            );
            $article_category_array = $this->searchArticleCategory( $c_arg_array );
            if (!$article_category_array)
                return array( 'code' => 404, 'message' => '分类信息没有找到' );

            //添加或修改文章信息
            $article_obj = new entity('wechat_content_article');
            if ($arg_array['article_id'] > 0) {
                $article_obj->article_id = $arg_array['article_id'];
                if (!$this->dbca->fetch($article_obj))
                    return array( 'code' => 404, 'message' => '信息没有找到' );
                $article_obj->editor = $arg_array['creator'];
            } else {
                $article_obj->creator = $arg_array['creator'];
            }

            if( $arg_array['activeType'] == 0 ){ //活动类型为“普通活动”

                $arg_array['code_startDate'] = '';
                $arg_array['code_endDate'] = '';
                $arg_array['use_startDate'] = '';
                $arg_array['use_endDate'] = '';
                $arg_array['useType'] = '';
                $arg_array['useTime'] = '';
                $arg_array['promotionID'] = '';

            }


            $article_obj->article_title = $arg_array['article_title'];
            $article_obj->article_summary = $arg_array['article_summary'];
            $article_obj->article_category_id = $article_category_array[0]['category_id'];
            $article_obj->article_category_index = $article_category_array[0]['category_index'];
            $article_obj->article_category_name = $article_category_array[0]['category_title'];
            $article_obj->description = $arg_array['description'];
            $article_obj->code_type =  $arg_array['code_type'];
            $article_obj->activeType =  $arg_array['activeType'];
            $article_obj->code_startDate = isset($arg_array['code_startDate'])?$arg_array['code_startDate']:'';
            $article_obj->code_endDate =  isset($arg_array['code_endDate'])?$arg_array['code_endDate']:'';
            $article_obj->use_startDate =  isset($arg_array['use_startDate'])?$arg_array['use_startDate']:'';
            $article_obj->use_endDate =  isset($arg_array['use_endDate'])?$arg_array['use_endDate']:'';
            $article_obj->limit_num =  isset($arg_array['limit_num'])?$arg_array['limit_num']:'';
            $article_obj->useType =  isset($arg_array['useType'])?$arg_array['useType']:'';
            $article_obj->useTime =  isset($arg_array['useTime'])?$arg_array['useTime']:'';
            $article_obj->promotionID =  isset($arg_array['promotionID'])?$arg_array['promotionID']:'';

            $this->dbca->save($article_obj);

            if ($arg_array['article_id'] > 0) {
                return array('code' => 200 , 'message' => '修改成功' , 'data' => $arg_array['article_id']);
            } else {
                return array('code' => 200 , 'message' => '保存成功' , 'data' => $this->dbca->insert_id);
            }

        } catch (Exception $e){
            error_log($e->getMessage());
            return array('code' => 500, 'message' => '系统错误');
        }
    }

    /**
     * 文章删除
     * @param $arg_array
     * @return array|null
     */
    public function deleteArticle(&$arg_array){

        if(!isset($arg_array['delArr'])){
            return array('code'=>400,'message'=>'参数错误');
        }

        $delArr = $arg_array['delArr'];

        try{

            //循环删除
            foreach( $delArr as $delObj ){

                $this->dbca->stmt_query('DELETE FROM wechat_content_article WHERE article_id = ?','i',$delObj);

            }

            return array('message'=>'删除成功', 'code'=>200);

        }catch( Exception $e ){

            error_log($e->getMessage());
            return null;

        }
    }

    /**
     * 文章禁用启用
     * @param $arg_array
     * @return array|null
     */
    public function changeArticleUseflg(&$arg_array){
        if(!isset($arg_array['article_id']) || !isset($arg_array['flg'])){
            return array('code'=>400,'message'=>'参数错误');
        }

        try{

            $content_article = new entity('wechat_content_article');
            $content_article->article_id = $arg_array['article_id'];

            if($this->dbca->fetch($content_article)){

                $content_article->useFlg = $arg_array['flg'];

                $this->dbca->save($content_article);

            }else{
                return array('code'=>400,'message'=>'不存在该分类');
            }

            if($arg_array['flg'] == 1){
                return array('code'=>200,'message'=>'微信CMS启用成功');
            }else{
                return array('code'=>200,'message'=>'微信CMS禁用成功');
            }

        }catch(Exception $e){

            error_log($e->getMessage());
            return null;

        }
    }

    /**
     * 关键词保存
     * @param unknown_type $arg_array
     */
    public function saveKeyWords( &$arg_array ){

        if (!isset($arg_array['keyword'] ,$arg_array['description'] , $arg_array['useFlg'],$arg_array['keyID'])){
            return (array( 'code' => 400, 'message' => '参数错误'));
        }

        if( empty($arg_array['replyID']) ){
            return (array( 'code' => 400, 'message' => '请添加回复内容'));
        }

        $keyWords = trim( $arg_array['keyword'] );

        $replyID_string = $arg_array['replyID'];//逗号“,”隔开

        $wechat_keywords = new entity('wechat_keywords');

        //如果单位号不为空则查询检查单位号
        if($arg_array['keyID'] != 0){
            $wechat_keywords->keyID = $arg_array['keyID'] ;
            if(!$this->dbca->fetch($wechat_keywords)){
                return (array( 'code' => 400, 'message' => sprintf('编号为「%d」,的关键词不存在,请核对后操作',$arg_array['keyID'])));
            }
            $wechat_keywords->editor = $arg_array['creator'] ;
        }else {
            $wechat_keywords->creator = $arg_array['creator'] ;
        }

        /********************** 检查关键词是否重复 ***********************/
        //查询出关键词为“$arg_array['keyword']”的所有信息
        $check_sql = 'SELECT * FROM wechat_keywords WHERE keyword=? AND level = ?';
        $check_result = $this->dbca->stmt_query($check_sql,'si',array($keyWords,1) );

        //检查该"关键词"是否已经存在
        if( $check_result ){
            if($arg_array['keyID'] != 0 && $check_result[0]->keyID != $arg_array['keyID'] ){
                return ( array('message'=>'关键词重复' , 'code'=>400 ) );
            }elseif( $arg_array['keyID'] == 0 ){
                return ( array('message'=>'关键词重复' , 'code'=>400 ) );
            }
        }

        //保存和更新关键字信息
        $wechat_keywords->keyword		= $keyWords;
        $wechat_keywords->description	= htmlspecialchars(trim($arg_array['description']));
        $wechat_keywords->useFlg		= $arg_array['useFlg'] ;
        $wechat_keywords->replyID		= $replyID_string ;
        $wechat_keywords->parentID		= isset( $_REQUEST['parentID']) && !empty($_REQUEST['parentID'] ) ? $_REQUEST['parentID'] : 0 ;
        $wechat_keywords->level		    = 1 ;
        $save_flg = $this->dbca->save( $wechat_keywords , 'wechat' ) ;
        if ($save_flg) {
            return (array( 'code' => 200, 'message' => '微信关键字保存成功' ));
        }else{
            return (array( 'code' => 500, 'message' => '微信关键字保存失败' ));
        }
    }

    /**
     * 删除关键词
     *
     */
    public function deleteKeyWord( &$arg_array ){

        //关键词编号串检查
        if ( !isset($arg_array['delete_str']) ){
            return (array( 'code' => 400, 'message' => '缺少参数' ));
        }

        if ( empty($arg_array['delete_str']) ){
            return (array( 'code' => 400, 'message' => '请选择要删除的关键词' ));
        }

        //将关键词编号串截成数组
        $delete_array = explode('_', $arg_array['delete_str']);

        //循环删除关键词
        try {
            $this->dbca->beginTransaction();
            foreach( $delete_array as &$u_l ) {
                if (!is_numeric( $u_l )){
                    return (array( 'code' => 400, 'message' => '参数错误' ));
                }

                //查询关键词信息
                $wechat_keywords = new entity('wechat_keywords');
                $wechat_keywords->keyID = $u_l;
                if ($this->dbca->fetch( $wechat_keywords )) {
                    $this->dbca->delete( $wechat_keywords );
                }

                //删除下级关键词
                $this->dbca->stmt_query( 'DELETE FROM wechat_keywords WHERE parentID = ?', 'i', $u_l );
            }

            $this->dbca->commit();

            return ( array( 'code' => 200, 'message' => '删除成功' ) );
        }catch (Exception $e){
            $this->dbca->rollBack();

            if ($e->getCode() > 0) {
                return ( array( 'code' => $e->getCode(), 'message' => $e->getMessage() ) );
            } else {
                return ( array( 'code' => 500, 'message' => '系统错误' ) );
            }
        }
    }

    /**
     * 更新关键词使用状态
     *
     * @param unknown_type $arg_array
     */
    public function actionKeyWords( &$arg_array ){

        //参数检查
        if ( !isset( $arg_array['useFlg_str'] ) || empty( $arg_array['useFlg_str'] ) ){
            return ( array( 'code' => 400, 'message' => '缺少参数' ) );
        }

        //获取参数数组
        $use_array = explode( '_', $arg_array['useFlg_str'] );

        //检查参数
        if( !isset($use_array[1]) || !in_array($use_array[1], array(0, 1)) ){
            return ( array( 'code' => 400, 'message' => '参数错误' ) );
        }

        //查询关键词是否存
        $wechat_keywords = new entity('wechat_keywords');
        $wechat_keywords->keyID = $use_array[0] ;
        if ( !$this->dbca->fetch( $wechat_keywords ) ) {
            return ( array( 'code' => 400, 'message' => sprintf('编号「%d」,的关键词不存在,请核对后操作',$use_array[0]) ) );
        }

        //更新状态
        $wechat_keywords->useFlg = $use_array[1] ;
        $this->dbca->save( $wechat_keywords , 'wechat' );

        if($use_array[1] == 1) {
            return ( array( 'code' => 200, 'message' => sprintf('编号「%d」,的关键词启用成功', $use_array[0]) ) );
        } else if ($use_array[1] == 0){
            return ( array( 'code' => 200, 'message' => sprintf('编号「%d」,的关键词禁用成功', $use_array[0]) ) );
        }
    }

    /**
     * 回复消息列表
     *
     * @param unknown_type $arg_array
     */
    public function autoReplyList( &$arg_array ){

        $replyIDstring = $arg_array['replyIDstring'];

        if( empty( $replyIDstring ) ){
            return ( array( 'code' => 400, 'message' => '请先选择回复' ) );
        }

        //截取字符串
        $replyIDstring = substr($replyIDstring, 1);

        $replay_array = array(
            'replyID_str' => $replyIDstring
        );

        $return_array = $this->searchAutoReply( $replay_array );

        return $return_array;

    }

    /**
     * 关键词回复内容列表
     */
    function searchKeyWordsCotent( $arg_array ){

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //内容ID
        if ( isset($arg_array['mapID']) && is_numeric($arg_array['mapID']) ) {
            $sql .= ' AND wkmm.mapID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['mapID'];
        }

        //关键词ID
        if ( isset($arg_array['keyID']) && is_numeric($arg_array['keyID']) ) {
            $sql .= ' AND wkmm.keyID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['keyID'];
        }

        //素材ID
        if ( isset($arg_array['materialID']) && is_numeric($arg_array['materialID']) ) {
            $sql .= ' AND wkmm.materialID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['materialID'];
        }

        //有效期开始日期
        if ( isset($arg_array['startDate']) && !empty($arg_array['startDate']) ) {
            $sql .= ' AND wkmm.startDate <= ?';
            $params_type .= 's';
            $params_array[] = $arg_array['startDate'];
        }

        //有效期结束日期
        if ( isset($arg_array['endDate']) && !empty($arg_array['endDate']) ) {
            $sql .= ' AND wkmm.endDate >= ?';
            $params_type .= 's';
            $params_array[] = $arg_array['endDate'];
        }

        //是否是主图片
        if ( isset($arg_array['isHost']) && in_array( $arg_array['isHost'] , array(0,1) ) ) {
            $sql .= ' AND wkmm.isHost = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['isHost'];
        }

        if( !empty( $arg_array['extendSql'] ) ){
            $sql .= $arg_array['extendSql'];
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count
                            FROM wechat_keywords_material_map wkmm
                            INNER JOIN wechat_material wm ON wkmm.materialID = wm.materialID ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询信息
            $search_sql = 'SELECT wkmm.mapID,wkmm.keyID,wkmm.startDate,wkmm.endDate,wkmm.isHost,
                        wm.materialID,wm.materialType,wm.materialTitle,wm.picLink,wm.description,wm.link,wm.article_id,wm.timeStamp,wm.createTime,
                        wm.media_id,wm.media_time
                        FROM wechat_keywords_material_map wkmm
                        INNER JOIN wechat_material wm ON wkmm.materialID = wm.materialID ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            foreach($temp_item_array as &$item) {
                $item_array[] = array(
                    'timeStamp'  => $item->timeStamp,
                    'createTime'  => $item->createTime,
                    'mapID'  => $item->mapID,
                    'keyID'=> $item->keyID,
                    'startDate' => $item->startDate,
                    'endDate' => $item->endDate,
                    'startTime' => date('Y-m-d' , strtotime($item->startDate)),
                    'endTime' => date('Y-m-d' , strtotime($item->endDate)),
                    'isHost' => $item->isHost,
                    'materialID' => $item->materialID,
                    'materialType' => $item->materialType,
                    'materialTitle' => $item->materialTitle,
                    'picLinkShow' => empty($item->picLink) ? '' : G_IMAGE_URL.$item->picLink,
                    'picLink' => $item->picLink,
                    'description' => $item->description,
                    'link' => $item->link,
                    'article_id' => $item->article_id,
                    'media_time' => $item->media_time,
                    'media_id' => $item->media_id
                );

            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;


        }

    }

    /**
     * 系统回复内容列表
     */
    function searchEventReply( $arg_array ){

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //内容ID
        if ( isset($arg_array['mapID']) && is_numeric($arg_array['mapID']) ) {
            $sql .= ' AND wemm.mapID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['mapID'];
        }

        //事件ID
        if ( isset($arg_array['eventID']) && is_numeric($arg_array['eventID']) ) {
            $sql .= ' AND wemm.eventID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['eventID'];
        }

        //素材ID
        if ( isset($arg_array['materialID']) && is_numeric($arg_array['materialID']) ) {
            $sql .= ' AND wemm.materialID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['materialID'];
        }

        //有效期开始日期
        if ( isset($arg_array['startDate']) && !empty($arg_array['startDate']) ) {
            $sql .= ' AND wemm.startDate <= ?';
            $params_type .= 's';
            $params_array[] = $arg_array['startDate'];
        }

        //有效期结束日期
        if ( isset($arg_array['endDate']) && !empty($arg_array['endDate']) ) {
            $sql .= ' AND wemm.endDate >= ?';
            $params_type .= 's';
            $params_array[] = $arg_array['endDate'];
        }

        //事件回复类型
        if ( isset($arg_array['eventType']) && in_array( $arg_array['eventType'] , array(1,2,3) ) ) {
            $sql .= ' AND wemm.eventType = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['eventType'];
        }

        //是否是主图片
        if ( isset($arg_array['isHost']) && in_array( $arg_array['isHost'] , array(0,1) ) ) {
            $sql .= ' AND wemm.isHost = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['isHost'];
        }

        if( !empty( $arg_array['extendSql'] ) ){
            $sql .= $arg_array['extendSql'];
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count
                            FROM wecaht_event_matetial_map wemm
                            INNER JOIN wechat_material wm ON wemm.materialID = wm.materialID ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询信息
            $search_sql = 'SELECT wemm.mapID,wemm.eventID,wemm.eventName,wemm.eventType,wemm.startDate,wemm.endDate,wemm.isHost,
                        wm.materialID,wm.materialType,wm.materialTitle,wm.picLink,wm.description,wm.link,wm.article_id,wm.timeStamp,wm.createTime,
                        wm.media_id,wm.media_time
                        FROM wecaht_event_matetial_map wemm
                        INNER JOIN wechat_material wm ON wemm.materialID = wm.materialID ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            foreach($temp_item_array as &$item) {
                $item_array[] = array(
                    'timeStamp'  => $item->timeStamp,
                    'createTime'  => $item->createTime,
                    'mapID'  => $item->mapID,
                    'eventID'=> $item->eventID,
                    'eventName' => $item->eventName,
                    'eventType' => $item->eventType,
                    'startDate' => $item->startDate,
                    'endDate' => $item->endDate,
                    'startTime' => date('Y-m-d' , strtotime($item->startDate)),
                    'endTime' => date('Y-m-d' , strtotime($item->endDate)),
                    'isHost' => $item->isHost,
                    'materialID' => $item->materialID,
                    'materialType' => $item->materialType,
                    'materialTitle' => $item->materialTitle,
                    'picLinkShow' => empty($item->picLink) ? '' : G_IMAGE_URL.$item->picLink,
                    'picLink' => $item->picLink,
                    'description' => $item->description,
                    'link' => $item->link,
                    'article_id' => $item->article_id,
                    'media_id' => $item->media_id,
                    'media_time' => $item->media_time
                );

            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;


        }

    }

    /**
     * 查询素材信息
     * @param array $arg_array 参数数组
     * @return array|null
     */
    function searchMaterial( &$arg_array ){

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //素材ID
        if ( isset($arg_array['materialID']) && is_numeric($arg_array['materialID']) && $arg_array['materialID'] > 0) {
            $sql .= ' AND materialID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['materialID'];
        }

        //素材类型：1、纯文本 2、图文
        if ( isset($arg_array['materialType']) && in_array($arg_array['materialType'], array(1, 2, 3, 4, 5)) ) {
            $sql .= ' AND materialType = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['materialType'];
        }

        //素材标题
        if ( isset($arg_array['materialTitle']) && !empty($arg_array['materialTitle']) ) {
            $sql .= ' AND materialTitle LIKE ?';
            $params_type .= 's';
            $params_array[] = '%' . $arg_array['materialTitle'] . '%';
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp'])) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM wechat_material ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询信息
            $search_sql = 'SELECT * FROM wechat_material ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            foreach($temp_item_array as &$item) {

                if ($item->article_id) {
                    //查询模板信息
                    $temp_arg_array = array(
                        'article_id' => $item->article_id
                    );
                    $article_array = $this->searchArticle( $temp_arg_array );
                    $article_array = $article_array[0];
                } else {
                    $article_array['article_title'] = '';
                    $article_array['description'] = '';
                }

                if ($item->materialType == 1) {
                    $materialTypeName = '纯文本';
                } else if ($item->materialType == 2) {
                    $materialTypeName = '图文';
                } else if ($item->materialType == 3) {
                    $materialTypeName = '多图文';
                } else if ($item->materialType == 4) {
                    $materialTypeName = '音频';
                } else if ($item->materialType == 5) {
                    $materialTypeName = '视频';
                } else {
                    $materialTypeName = '';
                }


                $item_array[] = array(
                    'materialID'  => $item->materialID,
                    'materialType'  => $item->materialType,
                    'materialTypeName'  => $materialTypeName,
                    'materialTitle'  => $item->materialTitle,
                    'picLink'  => G_IMAGE_URL . $item->picLink,
                    'description'  => $item->description,
                    'link'  => $item->link,
                    'article_id'  => $item->article_id,
                    'article_title' => $article_array['article_title'],
                    'article_description' => isset($arg_array['materialID']) ? htmlspecialchars_decode($article_array['description']) : ''
                );

            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;


        }

    }


    /**
     * 素材信息
     */
    function searchMaterialList( &$arg_array ){

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //素材ID
        if ( isset($arg_array['materialID']) && is_numeric($arg_array['materialID']) ) {
            $sql .= ' AND materialID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['materialID'];
        }

        //模板ID
        if ( isset($arg_array['article_id']) && is_numeric($arg_array['article_id']) ) {
            $sql .= ' AND article_id = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['article_id'];
        }

        //素材标题
        if ( isset($arg_array['materialTitle']) && !empty($arg_array['materialTitle']) ) {
            $sql .= ' AND materialTitle LIKE ?';
            $params_type .= 's';
            $params_array[] = '%'.$arg_array['materialTitle'].'%';
        }

        //素材描述
        if ( isset($arg_array['description']) && !empty($arg_array['description']) ) {
            $sql .= ' AND description LIKE ?';
            $params_type .= 's';
            $params_array[] = '%'.$arg_array['description'].'%';
        }

        //是否是主图片
        if ( isset($arg_array['materialType']) && in_array( $arg_array['materialType'] , array(1,2,3) ) ) {
            $sql .= ' AND materialType = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['materialType'];
        }

        if( !empty( $arg_array['extendSql'] ) ){
            $sql .= $arg_array['extendSql'];
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM wechat_material ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询信息
            $search_sql = 'SELECT * FROM wechat_material ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            foreach($temp_item_array as &$item) {
                $item_array[] = array(
                    'materialID'  => $item->materialID,
                    'materialType'=> $item->materialType,
                    'materialTitle' => $item->materialTitle,
                    'picLinkShow' => empty($item->picLink) ? '' : G_IMAGE_URL.$item->picLink,
                    'picLink' => $item->picLink,
                    'description' => $item->description,
                    'link' => $item->link,
                    'article_id' => $item->article_id
                );

            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }

    /**
     * 保存关键词
     */
    public function saveWechatKeyWords( $arg_array ){

        if( !isset( $arg_array['keyWords'] , $arg_array['description'] ) || empty( $arg_array['keyWords'] ) ){
            return array( 'code'=>400 , 'message'=>'参数错误' );
        }

        //接收参数
        $keyWords    = trim( $arg_array['keyWords'] );
        $description = trim( $arg_array['description'] );
        $keyID       = isset( $arg_array['keyID'] ) ? $arg_array['keyID'] : NULL;

        //第一步将关键词转化成小写
        $keyWords = strtolower( $keyWords );

        //第二步将关键词转化为半角
        $keyWords = $this->banjiao( $keyWords );

        try{

            //开启事务
            $this->dbca->beginTransaction();

            /********************** 检查关键词是否重复 ***********************/
            //查询出关键词为“$keyWords”的所有信息
            $check_sql = 'SELECT * FROM wechat_keywords WHERE keyword=? AND level = ?';
            $check_result = $this->dbca->stmt_query($check_sql,'si',array($keyWords,1) );

            //检查该"关键词"是否已经存在
            if( $check_result ){
                if ($keyID != 0 && $check_result[0]->keyID != $keyID ){
                    return ( array('message'=>'关键词重复' , 'code'=>400 ) );
                } else if ( empty($keyID) ){
                    return ( array('message'=>'关键词重复' , 'code'=>400 ) );
                }
            }

            //保存和更新关键字信息
            $wechat_keywords = new entity('wechat_keywords');

            if( $keyID ){

                $wechat_keywords->keyID	= $keyID;

                if( !$this->dbca->fetch($wechat_keywords) ){
                    return array( 'code'=>404 , 'message'=>'没有找到关键词信息' );
                }

            } else {
                $wechat_keywords->creator	= $arg_array['operator'];
            }

            $wechat_keywords->keyword		= $keyWords;
            $wechat_keywords->description	= htmlspecialchars($description);
            $wechat_keywords->useFlg		= 1 ;
            $wechat_keywords->parentID		= isset( $arg_array['parentID']) && !empty($arg_array['parentID'] ) ? $arg_array['parentID'] : 0 ;
            $wechat_keywords->level		    = 1 ;
            $wechat_keywords->isNeedReply   = isset( $arg_array['isNeedReply'] )? $arg_array['isNeedReply'] : 0;
            $wechat_keywords->replyType		= isset( $arg_array['replyType'] )? $arg_array['replyType'] : 0 ;

            $this->dbca->save( $wechat_keywords , 'wechat' ) ;

            if( empty($keyID) ){
                $keyID = $this->dbca->insert_id;
            }

            //如果传入关键词别名
            if( !empty( $arg_array['alias'] ) ){

                //删除之前的别名数据
                $delete_preAlias = 'DELETE FROM wechat_keywords_alias WHERE mainKeyWordsID=?';
                $this->dbca->stmt_query( $delete_preAlias , 'i' , $keyID );

                //去掉重复的关键词别名
                $arg_array['alias'] = array_unique( $arg_array['alias'] );

                foreach( $arg_array['alias'] as $alias ){

                    if( $alias == $keyWords ){
                        $isMain = 1;
                    } else {
                        $isMain = 0;
                    }

                    //第一步将关键词转化成小写
                    $alias = strtolower( $alias );

                    //第二步将关键词转化为半角
                    $alias = $this->banjiao( $alias );

                    //存储进关键词别名表中
                    $wechat_keywords_alias = new entity('wechat_keywords_alias');
                    $wechat_keywords_alias->aliasName = $alias;

                    if( $this->dbca->fetch( $wechat_keywords_alias ) ){
                        throw new Exception( '关键词别名['.$alias.']已存在' , 400 );
                    }

                    $wechat_keywords_alias->creator = $arg_array['operator'];
                    $wechat_keywords_alias->isMain = $isMain;
                    $wechat_keywords_alias->mainKeyWordsID = $keyID;

                    //保存
                    $this->dbca->save( $wechat_keywords_alias );

                }

            }

            //提交事务
            $this->dbca->commit();

            return array( 'code' => 200, 'message' => '保存成功' , 'data'=>$keyID );

        }catch (Exception $e){

            //回滚事务
            $this->dbca->rollBack();

            if( $e->getCode() > 0 ){

                return array('code' => $e->getCode() , 'message' => $e->getMessage() );
            } else {
                error_log( $e->getMessage() );
                return array('code' => 500, 'message' => '系统错误，保存失败' );
            }

        }

    }

    /**
     * 检查关键词回复内容排期是否重复
     * $keyID  关键词ID
     * $mapID  内容ID
     */
    public function checkRepeatDate( $arg_array ){

        if( !isset( $arg_array['keyID'] ) || !is_numeric( $arg_array['keyID'] ) || empty( $arg_array['keyID'] ) ){
            return array( 'code'=>400 , '缺少参数' );
        }

        if( empty( $arg_array['startDate'] ) || empty( $arg_array['endDate'] ) ){
            return array( 'code'=>400 , '缺少参数' );
        }

        //查询SQL
        $sql = ' SELECT * FROM wechat_keywords_material_map WHERE keyID=%d AND ( ( startDate <= %s AND endDate >= %s  ) OR ( startDate <= %s AND endDate >= %s ) OR ( startDate >= %s AND endDate <= %s ) ) ';

        //存在mapID时的查询SQL
        $sql_edit = ' SELECT * FROM wechat_keywords_material_map WHERE keyID=%d AND mapID <> %d AND ( ( startDate <= %s AND endDate >= %s  ) OR ( startDate <= %s AND endDate >= %s ) OR ( startDate >= %s AND endDate <= %s ) ) ';

        //校验排期是否重复SQL
        if( $arg_array['mapID'] > 0 ){

            $check_sql = sprintf( $sql_edit , $arg_array['keyID'] , $arg_array['mapID'] , '\''.$arg_array['startDate'].'\'' , '\''.$arg_array['startDate'].'\'' , '\''.$arg_array['endDate'].'\'', '\''.$arg_array['endDate'].'\'' , '\''.$arg_array['startDate'].'\'' , '\''.$arg_array['endDate'].'\'');

        } else {

            $check_sql = sprintf( $sql , $arg_array['keyID'] , '\''.$arg_array['startDate'].'\'' , '\''.$arg_array['startDate'].'\'' , '\''.$arg_array['endDate'].'\'', '\''.$arg_array['endDate'].'\'', '\''.$arg_array['startDate'].'\'' , '\''.$arg_array['endDate'].'\'');

        }

        //查询结果
        $result = $this->dbca->stmt_query( $check_sql );

        if( $result ){
            return array( 'code'=>200 , 'data'=>1 );
        } else {
            return array( 'code'=>200 , 'data'=>0 );
        }

    }

    /**
     * 保存关键词单图文回复
     */
    public function saveOneNewsReply( $arg_array ){

        quanli_include('module/base/fileDirHandler.class.php');

        //实例化类
        $fileDirHandler = new fileDirHandler();

        //实例公共类
        $commHandler = new commHandler();

        if( !isset( $arg_array['keyID'], $arg_array['title'], $arg_array['picLink'], $arg_array['startDate'], $arg_array['endDate'], $arg_array['link'], $arg_array['description'], $arg_array['summary'] )) {
            return array( 'code'=>400 , 'message'=>'参数错误');
        }
        if (!is_numeric($arg_array['keyID'])) {
            return array( 'code'=>400 , 'message'=>'参数错误');
        }

        if (empty($arg_array['title'])) {
            return array( 'code'=>400 , 'message'=>'标题不能为空');
        }
        if (empty($arg_array['picLink'])) {
            return array( 'code'=>400 , 'message'=>'请上传图片');
        }
        if (!$commHandler->isDate($arg_array['startDate'])) {
            return array( 'code'=>400 , 'message'=>'开始时间不能为空');
        }
        if (!$commHandler->isDate($arg_array['endDate'])) {
            return array( 'code'=>400 , 'message'=>'结束时间不能为空');
        }
        if ($arg_array['startDate'] > $arg_array['endDate']) {
            return array( 'code'=>400 , 'message'=>'开始时间不能大于结束时间');
        }

        if ( !empty($arg_array['link']) ) {
            $arg_array['description'] = null;
        } else {
            if (empty($arg_array['description'])) {
                return array( 'code'=>400 , 'message'=>'正文内容不能为空');
            }
            $arg_array['link'] = null;
        }

        if (!isset($arg_array['mapID']) || !is_numeric($arg_array['mapID']) || $arg_array['mapID'] <= 0) {
            $arg_array['mapID'] = 0;
        }

        if (!isset($arg_array['materialID']) || !is_numeric($arg_array['materialID']) || $arg_array['materialID'] <= 0) {
            $arg_array['materialID'] = 0;
        }

        try {

            //查询关键词
            $temp_array = array(
                'keyID' => $arg_array['keyID']
            );
            $keywords_array = $this->searchKeyWords( $temp_array );
            if (!$keywords_array) {
                throw new Exception('关键词信息没有找到', 404);
            }
            if ( !in_array($arg_array['keyType'], array(1 , 2, 3)) ) {
                throw new Exception('关键词信息没有找到', 404);
            }


            //保存(更新)关键词映射
            $wechat_keywords_material_map = new entity('wechat_keywords_material_map');
            $wechat_keywords_material_map->keyID = $arg_array['keyID'];
            if( $arg_array['mapID'] > 0 ){

                $wechat_keywords_material_map->mapID = $arg_array['mapID'];
                if (!$this->dbca->fetch($wechat_keywords_material_map)) {
                    throw new Exception('回复内容信息没有找到', 404);
                }

            } else {

                //实例化公共类
                $commHandler = new commHandler($this->dbca);

                //获取映射ID自增量
                $arg_array['mapID'] = $commHandler->generate_seqno('seqno_wechatmap');

                $wechat_keywords_material_map->mapID = $arg_array['mapID'];

                $wechat_keywords_material_map->creator = $arg_array['operator'];
            }

            //检查排期是否冲突
            $temp_array['mapID'] = $arg_array['mapID'];
            $temp_array['startDate'] = $arg_array['startDate'];
            $temp_array['endDate'] = $arg_array['endDate'];
            $checkResult = $this->checkRepeatDate( $temp_array );
            if ( $checkResult['code'] == 200 && $checkResult['data'] == 1 ) {
                throw new Exception('当前时间段已有其他回复内容', 404);
            }

            //如果链接为空，则保存/更新cms内容
            if ( empty($arg_array['link']) && $arg_array['selectedFlg'] == 0 ) {

                $temp_array = array(
                    'creator' => $arg_array['operator'],
                    'article_id' => $arg_array['cmsID'],
                    'article_title' => $arg_array['title'],
                    'code_type' => $arg_array['code_type'],
                    'activeType' => $arg_array['activeType'],
                    'code_startDate' => $arg_array['code_startDate'],
                    'code_endDate' => $arg_array['code_endDate'],
                    'use_startDate' => $arg_array['use_startDate'],
                    'use_endDate' => $arg_array['use_endDate'],
                    'limit_num' => $arg_array['limit_num'],
                    'useType' => $arg_array['useType'],
                    'useTime' => $arg_array['useTime'],
                    'article_summary' => $arg_array['summary'],
                    'description' => $arg_array['description'],
                    'promotionID' => $arg_array['promotionID'],
                    'category_id' => 6
                );
                $article_array = $this->saveArticleInfo( $temp_array );
                if ($article_array['code'] != 200) {
                    throw new Exception($article_array['message'], 404);
                }
                $arg_array['article_id'] = $article_array['data'];

                if( $arg_array['cmsID'] > 0 ){
                    //删除排期缓存
                    $dir = G_APPLICATION_BASEPATH.'/wap/html_cache/'.$_SERVER['SERVER_NAME'].'/display/display-'.$arg_array['cmsID'].'.html';
                    system('rm -fr ' . $dir);
                }

            }

            //页面“选择”模板
            if( $arg_array['cmsID'] > 0 &&  $arg_array['selectedFlg'] == 1){
                $arg_array['article_id'] = $arg_array['cmsID'];
            }

            //存在链接时，清空模板ID
            if( !empty( $arg_array['link'] ) || ( empty($arg_array['cmsID']) && !isset($arg_array['article_id']) ) ){
                $arg_array['article_id'] = NULL;
            }

            //保存(更新)素材
            $wechat_material = new entity('wechat_material');
            if( $arg_array['materialID'] > 0 ){

                $wechat_material->materialID = $arg_array['materialID'];
                if (!$this->dbca->fetch($wechat_material)) {
                    throw new Exception('回复内容信息没有找到', 404);
                }

            } else {
                $wechat_material->creator = $arg_array['operator'];
            }

            //将图片路径打成数组
            $picture_array = explode( '/' , $arg_array['picLink'] );

            //转移图片路径
            if( $picture_array[0] == '' || $picture_array[1] == 'quanliadmin' ){

                if( ($arg_array['mapID'] &&  $arg_array['picLink'] != $wechat_material->picLink) || empty($arg_array['mapID']) ){

                    $oldName = G_APPLICATION_BASEPATH . $arg_array['picLink'];
                    $newName = G_IMAGE_SAVE_ROOT . 'wechat/cotent/' . $fileDirHandler->basename($oldName);

                    if (!$fileDirHandler->move($oldName, $newName)) {
                        throw new Exception('文件移动失败', 404);
                    }

                    $arg_array['picLink'] = 'wechat/cotent/' . $fileDirHandler->basename($oldName);

                }

            }

            $wechat_material->materialType = $arg_array['keyType'];
            $wechat_material->materialTitle = $arg_array['title'];
            $wechat_material->link = $arg_array['link'];
            $wechat_material->picLink = $arg_array['picLink'];
            $wechat_material->description = $arg_array['summary'];
            $wechat_material->article_id = $arg_array['article_id'];
            $this->dbca->save($wechat_material);

            if( $arg_array['materialID'] == 0 ){
                $arg_array['materialID'] = $this->dbca->insert_id;
            }

            //保存(更新)映射表信息
            $wechat_keywords_material_map->materialID = $arg_array['materialID'];
            $wechat_keywords_material_map->startDate = $arg_array['startDate'];
            $wechat_keywords_material_map->endDate = $arg_array['endDate'];

            //保存映射表信息
            $this->dbca->save( $wechat_keywords_material_map );

            return array( 'code'=> 200 , 'message' => '保存成功', 'data' => $arg_array['mapID'] );


        } catch (Exception $e){

            if( $e->getCode() > 0 ){

                return array( 'code'=>$e->getCode() , 'message'=>$e->getMessage() );

            } else {

                error_log( $e->getMessage() );
                return array( 'code'=>500 , 'message'=>$e->getMessage() );

            }

        }

    }

    /**
     * 保存关键词文本回复
     */
    public function saveTextReply( $arg_array ){

        if( !isset( $arg_array['keyID'], $arg_array['content'],  $arg_array['startDate'], $arg_array['endDate'], $arg_array['link'], $arg_array['description'], $arg_array['summary'] )) {
            return array( 'code'=>400 , 'message'=>'参数错误');
        }

        if( !is_numeric( $arg_array['keyID'] ) ){
            return array( 'code'=>400 , 'message'=>'参数错误');
        }

        if( empty( $arg_array['content'] ) ){
            return array( 'code'=>400 , 'message'=>'请输入文本内容');
        }

        if( empty( $arg_array['startDate'] ) ){
            return array( 'code'=>400 , 'message'=>'开始时间不能为空');
        }

        if( empty( $arg_array['endDate'] ) ){
            return array( 'code'=>400 , 'message'=>'结束时间不能为空');
        }

        if( $arg_array['startDate'] > $arg_array['endDate'] ){
            return array( 'code'=>400 , 'message'=>'开始时间不能大于结束时间');
        }

        if( !empty($arg_array['link']) ){

            $arg_array['description'] = NULL;

        } else {

            if( !empty($arg_array['description']) ){

                if( empty( $arg_array['title'] ) ){
                    return array( 'code'=>400 , 'message'=>'标题不能为空');
                }

                $arg_array['link'] = NULL;

            }

        }

        if (!isset($arg_array['mapID']) || !is_numeric($arg_array['mapID']) || $arg_array['mapID'] <= 0) {
            $arg_array['mapID'] = 0;
        }

        if (!isset($arg_array['materialID']) || !is_numeric($arg_array['materialID']) || $arg_array['materialID'] <= 0) {
            $arg_array['materialID'] = 0;
        }

        try{

            //查询关键词
            $temp_array = array(
                'keyID' => $arg_array['keyID']
            );
            $keywords_array = $this->searchKeyWords( $temp_array );
            if (!$keywords_array) {
                throw new Exception('关键词信息没有找到', 404);
            }
            if ( !in_array($arg_array['keyType'], array(1 , 2, 3)) ) {
                throw new Exception('关键词信息没有找到', 404);
            }

            //保存(更新)关键词映射
            $wechat_keywords_material_map = new entity('wechat_keywords_material_map');
            $wechat_keywords_material_map->keyID = $arg_array['keyID'];
            if( $arg_array['mapID'] > 0 ){

                $wechat_keywords_material_map->mapID = $arg_array['mapID'];
                if (!$this->dbca->fetch($wechat_keywords_material_map)) {
                    throw new Exception('回复内容信息没有找到', 404);
                }

            } else {

                //实例化公共类
                $commHandler = new commHandler($this->dbca);

                //获取映射ID自增量
                $arg_array['mapID'] = $commHandler->generate_seqno('seqno_wechatmap');

                $wechat_keywords_material_map->mapID = $arg_array['mapID'];

                $wechat_keywords_material_map->creator = $arg_array['operator'];
            }

            //检查排期是否冲突
            $temp_array['mapID'] = $arg_array['mapID'];
            $temp_array['startDate'] = $arg_array['startDate'];
            $temp_array['endDate'] = $arg_array['endDate'];
            $checkResult = $this->checkRepeatDate( $temp_array );
            if ( $checkResult['code'] == 200 && $checkResult['data'] == 1 ) {
                throw new Exception('当前时间段已有其他回复内容', 404);
            }

            //如果链接为空,正文不为空,则保存CMS
            if( empty($arg_array['link']) && !empty( $arg_array['description'] ) && $arg_array['selectedFlg'] == 0){

                $temp_array = array(
                    'creator' => $arg_array['operator'],
                    'article_id' => $arg_array['cmsID'],
                    'article_title' => $arg_array['title'],
                    'code_type' => $arg_array['code_type'],
                    'activeType' => $arg_array['activeType'],
                    'code_startDate' => $arg_array['code_startDate'],
                    'code_endDate' => $arg_array['code_endDate'],
                    'use_startDate' => $arg_array['use_startDate'],
                    'use_endDate' => $arg_array['use_endDate'],
                    'limit_num' => $arg_array['limit_num'],
                    'useType' => $arg_array['useType'],
                    'useTime' => $arg_array['useTime'],
                    'article_summary' => $arg_array['summary'],
                    'description' => $arg_array['description'],
                    'promotionID' => $arg_array['promotionID'],
                    'category_id' => 6
                );

                $article_array = $this->saveArticleInfo( $temp_array );
                if ($article_array['code'] != 200) {
                    throw new Exception($article_array['message'], 404);
                }
                $arg_array['article_id'] = $article_array['data'];

                if( $arg_array['cmsID'] > 0 ){
                    //删除排期缓存
                    $dir = G_APPLICATION_BASEPATH.'/wap/html_cache/'.$_SERVER['SERVER_NAME'].'/display/display-'.$arg_array['cmsID'].'.html';
                    system('rm -fr ' . $dir);
                }

            }

            //页面“选择”模板
            if( $arg_array['cmsID'] > 0 &&  $arg_array['selectedFlg'] == 1){
                $arg_array['article_id'] = $arg_array['cmsID'];
            }

            //存在链接时，清空模板ID
            if( !empty( $arg_array['link'] ) || ( empty($arg_array['cmsID']) && !isset($arg_array['article_id']) ) ){
                $arg_array['article_id'] = NULL;
            }

            //保存(更新)素材
            $wechat_material = new entity('wechat_material');
            if( $arg_array['materialID'] > 0 ){

                $wechat_material->materialID = $arg_array['materialID'];
                if (!$this->dbca->fetch($wechat_material)) {
                    throw new Exception('回复内容信息没有找到', 404);
                }

            } else {
                $wechat_material->creator = $arg_array['operator'];
            }

            $wechat_material->materialType = $arg_array['keyType'];
            $wechat_material->materialTitle = $arg_array['title'];
            $wechat_material->description = $arg_array['content'];
            $wechat_material->link = $arg_array['link'];
            $wechat_material->article_id = $arg_array['article_id'];
            $this->dbca->save($wechat_material);

            if( $arg_array['materialID'] == 0 ){
                $arg_array['materialID'] = $this->dbca->insert_id;
            }

            //保存(更新)映射表信息
            $wechat_keywords_material_map->materialID = $arg_array['materialID'];
            $wechat_keywords_material_map->startDate = $arg_array['startDate'];
            $wechat_keywords_material_map->endDate = $arg_array['endDate'];

            //保存映射表信息
            $this->dbca->save( $wechat_keywords_material_map );

            return array( 'code'=> 200 , 'message' => '保存成功', 'data' => $arg_array['mapID'] );

        }catch ( Exception $e ){

            if( $e->getCode() > 0 ){

                return array( 'code'=>$e->getCode() , 'message'=>$e->getMessage() );

            } else {

                error_log( $e->getMessage() );
                return array( 'code'=>500 , 'message'=>$e->getMessage() );

            }

        }

    }

    /**
     * 保存关键词多图文
     */
    public function savekeyWordsMoreNews( $arg_array ){

        if( !isset( $arg_array['keyID'],$arg_array['startDate'], $arg_array['endDate'])) {
            return array( 'code'=>400 , 'message'=>'参数错误');
        }

        if( !is_numeric( $arg_array['keyID'] ) ){
            return array( 'code'=>400 , 'message'=>'参数错误');
        }

        if( empty( $arg_array['startDate'] ) ){
            return array( 'code'=>400 , 'message'=>'开始时间不能为空');
        }

        if( empty( $arg_array['endDate'] ) ){
            return array( 'code'=>400 , 'message'=>'结束时间不能为空');
        }

        if( $arg_array['startDate'] > $arg_array['endDate'] ){
            return array( 'code'=>400 , 'message'=>'开始时间不能大于结束时间');
        }

        if( empty($arg_array['subArray']) || !is_array($arg_array['subArray']) ){
            return array( 'code'=>400 , 'message'=>'多图文最少需要两条信息');
        } else {

            if( count($arg_array['subArray']) < 2 ){
                return array( 'code'=>400 , 'message'=>'多图文最少需要两条信息');
            }

        }

        if (!isset($arg_array['mapID']) || !is_numeric($arg_array['mapID']) || $arg_array['mapID'] <= 0) {
            $arg_array['mapID'] = 0;
        }

        try{

            //开启事务
            $this->dbca->beginTransaction();

            //查询关键词
            $temp_array = array(
                'keyID' => $arg_array['keyID']
            );
            $keywords_array = $this->searchKeyWords( $temp_array );
            if (!$keywords_array) {
                throw new Exception('关键词信息没有找到', 404);
            }

            //保存(更新)关键词映射
            $wechat_keywords_material_map = new entity('wechat_keywords_material_map');
            $wechat_keywords_material_map->keyID = $arg_array['keyID'];
            if( $arg_array['mapID'] > 0 ){

                $wechat_keywords_material_map->mapID = $arg_array['mapID'];
                if (!$this->dbca->fetch($wechat_keywords_material_map)) {
                    throw new Exception('回复内容信息没有找到', 404);
                }

            } else {

                //实例化公共类
                $commHandler = new commHandler($this->dbca);

                //获取映射ID自增量
                $arg_array['mapID'] = $commHandler->generate_seqno('seqno_wechatmap');

                $wechat_keywords_material_map->mapID = $arg_array['mapID'];

                $wechat_keywords_material_map->creator = $arg_array['operator'];
            }

            //检查排期是否冲突
            $temp_array['mapID'] = $arg_array['mapID'];
            $temp_array['startDate'] = $arg_array['startDate'];
            $temp_array['endDate'] = $arg_array['endDate'];
            $checkResult = $this->checkRepeatDate( $temp_array );
            if ( $checkResult['code'] == 200 && $checkResult['data'] == 1 ) {
                throw new Exception('当前时间段已有其他回复内容', 404);
            }

            $wechat_keywords_material_map->materialID = $arg_array['subArray'][0];
            $wechat_keywords_material_map->startDate  = $arg_array['startDate'];
            $wechat_keywords_material_map->endDate    = $arg_array['endDate'];
            $wechat_keywords_material_map->isHost     = 1;

            $this->dbca->save( $wechat_keywords_material_map );

            //删除该排期ID下的映射信息
            $delete_map = 'DELETE FROM wechat_news_map WHERE mapID=?';
            $this->dbca->stmt_query( $delete_map , 'i' , $arg_array['mapID'] );

            //保存映射信息
            foreach ( $arg_array['subArray'] as $key=>$materialID ) {

                //查询素材信息
                $materialInfo = new entity('wechat_material');
                $materialInfo->materialID = $materialID;
                if( !$this->dbca->fetch( $materialInfo ) ){
                    throw new Exception('图文信息有误' , 404);
                }

                if( $materialInfo->link == '' && empty($materialInfo->article_id) ){

                    if( $key == 0 ){
                        $err_msg = '主图文正文不能为空';
                    } else {
                        $err_msg = '第'.$key.'行子图文正文不能为空';
                    }

                    throw new Exception($err_msg , 404);
                }

                //多图文映射表
                $wechat_news_map = new entity('wechat_news_map');
                $wechat_news_map->mapID = $arg_array['mapID'];
                $wechat_news_map->materialID = $materialID;
                $wechat_news_map->sortOrder = $key+1;

                $this->dbca->save($wechat_news_map);

            }

            //提交事务
            $this->dbca->commit();

            return array( 'code'=> 200 , 'message' => '保存成功', 'data' => $arg_array['mapID'] );

        }catch (Exception $e){

            //回滚事务
            $this->dbca->rollBack();

            if( $e->getCode() > 0 ){

                return array( 'code'=>$e->getCode() , 'message'=>$e->getMessage() );

            } else {

                error_log( $e->getMessage() );
                return array( 'code'=>500 , 'message'=>$e->getMessage() );

            }

        }

    }

    /**
     * 保存关键词多媒体回复
     */
    public function savekeyWordsMedia( $arg_array ){

        if( !isset( $arg_array['keyID'],$arg_array['keyType'],$arg_array['media_id'],$arg_array['materialLink'],$arg_array['startDate'], $arg_array['endDate'])) {
            return array( 'code'=>400 , 'message'=>'参数错误');
        }

        if( !is_numeric( $arg_array['keyID'] ) ){
            return array( 'code'=>400 , 'message'=>'参数错误');
        }

        if( empty( $arg_array['materialLink'] ) ){
            if( $arg_array['keyType'] == 4 ){
                return array( 'code'=>400 , 'message'=>'请上传音频文件');
            } else {
                return array( 'code'=>400 , 'message'=>'请上传视频文件');
            }
        }

        //视频需要填写标题
        if( $arg_array['keyType'] == 5 && empty($arg_array['title']) ){
            return array( 'code'=>400 , 'message'=>'请输入1到64个字的标题');
        }

        if( empty( $arg_array['startDate'] ) ){
            return array( 'code'=>400 , 'message'=>'开始时间不能为空');
        }

        if( empty( $arg_array['endDate'] ) ){
            return array( 'code'=>400 , 'message'=>'结束时间不能为空');
        }

        if( $arg_array['startDate'] > $arg_array['endDate'] ){
            return array( 'code'=>400 , 'message'=>'开始时间不能大于结束时间');
        }

        if (!isset($arg_array['mapID']) || !is_numeric($arg_array['mapID']) || $arg_array['mapID'] <= 0) {
            $arg_array['mapID'] = 0;
        }

        if (!isset($arg_array['materialID']) || !is_numeric($arg_array['materialID']) || $arg_array['materialID'] <= 0) {
            $arg_array['materialID'] = 0;
        }

        if( isset($arg_array['summary']) && !empty($arg_array['summary']) ){
            $arg_array['summary'] = htmlspecialchars($arg_array['summary']);
        } else {
            $arg_array['summary'] = '';
        }

        try{

            //开启事务
            $this->dbca->beginTransaction();

            //查询关键词
            $temp_array = array(
                'keyID' => $arg_array['keyID']
            );
            $keywords_array = $this->searchKeyWords( $temp_array );
            if (!$keywords_array) {
                throw new Exception('关键词信息没有找到', 404);
            }

            //保存(更新)关键词映射
            $wechat_keywords_material_map = new entity('wechat_keywords_material_map');
            $wechat_keywords_material_map->keyID = $arg_array['keyID'];
            if( $arg_array['mapID'] > 0 ){

                $wechat_keywords_material_map->mapID = $arg_array['mapID'];
                if (!$this->dbca->fetch($wechat_keywords_material_map)) {
                    throw new Exception('回复内容信息没有找到', 404);
                }

            } else {

                //实例化公共类
                $commHandler = new commHandler($this->dbca);

                //获取映射ID自增量
                $arg_array['mapID'] = $commHandler->generate_seqno('seqno_wechatmap');

                $wechat_keywords_material_map->mapID = $arg_array['mapID'];

                $wechat_keywords_material_map->creator = $arg_array['operator'];
            }

            //检查排期是否冲突
            $temp_array['mapID'] = $arg_array['mapID'];
            $temp_array['startDate'] = $arg_array['startDate'];
            $temp_array['endDate'] = $arg_array['endDate'];
            $checkResult = $this->checkRepeatDate( $temp_array );
            if ( $checkResult['code'] == 200 && $checkResult['data'] == 1 ) {
                throw new Exception('当前时间段已有其他回复内容', 404);
            }

            //保存(更新)素材
            $wechat_material = new entity('wechat_material');
            if( $arg_array['materialID'] > 0 ){

                $wechat_material->materialID = $arg_array['materialID'];
                if (!$this->dbca->fetch($wechat_material)) {
                    throw new Exception('回复内容信息没有找到', 404);
                }

                //若上传了新的媒体文件，则更新媒体文件上传时间
                if( $wechat_material->media_id != $arg_array['media_id'] ){
                    $wechat_material->media_time = date('Y-m-d H:i:s');
                }

            } else {
                $wechat_material->creator    = $arg_array['operator'];
                $wechat_material->media_time = date('Y-m-d H:i:s');
            }

            $wechat_material->materialType  = $arg_array['keyType'];
            $wechat_material->materialTitle = isset($arg_array['title'])?$arg_array['title']:'';
            $wechat_material->picLink       = $arg_array['materialLink'];
            $wechat_material->description   = $arg_array['summary'];
            $wechat_material->media_id      = $arg_array['media_id'];
            $this->dbca->save($wechat_material);

            if( $arg_array['materialID'] == 0 ){
                $arg_array['materialID'] = $this->dbca->insert_id;
            }

            $wechat_keywords_material_map->materialID = $arg_array['materialID'];
            $wechat_keywords_material_map->startDate  = $arg_array['startDate'];
            $wechat_keywords_material_map->endDate    = $arg_array['endDate'];

            $this->dbca->save( $wechat_keywords_material_map );

            //提交事务
            $this->dbca->commit();

            return array( 'code'=> 200 , 'message' => '保存成功', 'data' => $arg_array['mapID'] );

        }catch (Exception $e){

            //回滚事务
            $this->dbca->rollBack();

            if( $e->getCode() > 0 ){

                return array( 'code'=>$e->getCode() , 'message'=>$e->getMessage() );

            } else {

                error_log( $e->getMessage() );
                return array( 'code'=>500 , 'message'=>$e->getMessage() );

            }

        }

    }

    /**
     * 删除关键词排期
     */
    public function deleteKeywordsMap( $arg_array ){

        if( !isset( $arg_array['keyID'] , $arg_array['mapID']) || !is_numeric($arg_array['keyID']) || !is_numeric($arg_array['mapID']) ){
            return array( 'code'=>400 , 'message'=>'参数错误' );
        }

        try{

            //查询关键词排期信息
            $map_obj = new entity('wechat_keywords_material_map');
            $map_obj->mapID = $arg_array['mapID'];
            $map_obj->keyID = $arg_array['keyID'];

            if( !$this->dbca->fetch( $map_obj ) ){
                throw new Exception( '排期信息没找到' , 404 );
            }

            //删除
            $this->dbca->delete( $map_obj );

            return array( 'code'=>200 , 'message'=>'删除成功' , 'data'=>$arg_array['mapID'] );

        }catch (Exception $e){

            if( $e->getCode() > 0 ){

                return array( 'code'=>$e->getCode() , 'message'=>$e->getMessage() );

            } else {

                error_log( $e->getMessage() );
                return array( 'code'=>500 , 'message'=>$e->getMessage() );

            }

        }

    }

    /**
     * 检查系统回复内容排期是否重复
     * $eventID  事件ID
     * $mapID  内容ID
     */
    public function checkSystemRepeatDate( $arg_array ){

        if( !isset( $arg_array['eventID'] ) || !is_numeric( $arg_array['eventID'] ) || empty( $arg_array['eventID'] ) ){
            return array( 'code'=>400 , '缺少参数' );
        }

        if( empty( $arg_array['startDate'] ) || empty( $arg_array['endDate'] ) ){
            return array( 'code'=>400 , '缺少参数' );
        }

        //查询SQL
        $sql = ' SELECT * FROM wecaht_event_matetial_map WHERE eventID=%d AND ( ( startDate <= %s AND endDate >= %s  ) OR ( startDate <= %s AND endDate >= %s ) OR ( startDate >= %s AND endDate <= %s ) ) ';

        //存在mapID时的查询SQL
        $sql_edit = ' SELECT * FROM wecaht_event_matetial_map WHERE eventID=%d AND mapID <> %d AND ( ( startDate <= %s AND endDate >= %s  ) OR ( startDate <= %s AND endDate >= %s ) OR ( startDate >= %s AND endDate <= %s ) ) ';

        //校验排期是否重复SQL
        if( $arg_array['mapID'] > 0 ){

            $check_sql = sprintf( $sql_edit , $arg_array['eventID'] , $arg_array['mapID'] , '\''.$arg_array['startDate'].'\'' , '\''.$arg_array['startDate'].'\'' , '\''.$arg_array['endDate'].'\'', '\''.$arg_array['endDate'].'\'' , '\''.$arg_array['startDate'].'\'' , '\''.$arg_array['endDate'].'\'');

        } else {

            $check_sql = sprintf( $sql , $arg_array['eventID'] , '\''.$arg_array['startDate'].'\'' , '\''.$arg_array['startDate'].'\'' , '\''.$arg_array['endDate'].'\'', '\''.$arg_array['endDate'].'\'', '\''.$arg_array['startDate'].'\'' , '\''.$arg_array['endDate'].'\'');

        }

        //查询结果
        $result = $this->dbca->stmt_query( $check_sql );

        if( $result ){
            return array( 'code'=>200 , 'data'=>1 );
        } else {
            return array( 'code'=>200 , 'data'=>0 );
        }

    }

    /**
     * 保存系统事件多媒体回复
     */
    public function saveSystemMedia($arg_array){

        if( !isset( $arg_array['eventID'],$arg_array['eventName'],$arg_array['media_id'],$arg_array['materialLink'],$arg_array['startDate'], $arg_array['endDate'])) {
            return array( 'code'=>400 , 'message'=>'参数错误');
        }

        if( !is_numeric( $arg_array['eventID'] ) ){
            return array( 'code'=>400 , 'message'=>'参数错误');
        }

        if( empty( $arg_array['materialLink'] ) ){
            if( $arg_array['eventType'] == 4 ){
                return array( 'code'=>400 , 'message'=>'请上传音频文件');
            } else {
                return array( 'code'=>400 , 'message'=>'请上传视频文件');
            }
        }

        //视频需要填写标题
        if( $arg_array['eventType'] == 5 && empty($arg_array['title']) ){
            return array( 'code'=>400 , 'message'=>'请输入1到64个字的标题');
        }

        if( empty( $arg_array['startDate'] ) ){
            return array( 'code'=>400 , 'message'=>'开始时间不能为空');
        }

        if( empty( $arg_array['endDate'] ) ){
            return array( 'code'=>400 , 'message'=>'结束时间不能为空');
        }

        if( $arg_array['startDate'] > $arg_array['endDate'] ){
            return array( 'code'=>400 , 'message'=>'开始时间不能大于结束时间');
        }

        if (!isset($arg_array['mapID']) || !is_numeric($arg_array['mapID']) || $arg_array['mapID'] <= 0) {
            $arg_array['mapID'] = 0;
        }

        if (!isset($arg_array['materialID']) || !is_numeric($arg_array['materialID']) || $arg_array['materialID'] <= 0) {
            $arg_array['materialID'] = 0;
        }

        if( isset($arg_array['summary']) && !empty($arg_array['summary']) ){
            $arg_array['summary'] = htmlspecialchars($arg_array['summary']);
        } else {
            $arg_array['summary'] = '';
        }

        try{

            //开启事务
            $this->dbca->beginTransaction();

            //保存(更新)系统事件映射
            $wecaht_event_matetial_map = new entity('wecaht_event_matetial_map');
            $wecaht_event_matetial_map->eventID = $arg_array['eventID'];
            if( $arg_array['mapID'] > 0 ){

                $wecaht_event_matetial_map->mapID = $arg_array['mapID'];
                if (!$this->dbca->fetch($wecaht_event_matetial_map)) {
                    throw new Exception('回复内容信息没有找到', 404);
                }

            } else {

                //实例化公共类
                $commHandler = new commHandler($this->dbca);

                //获取映射ID自增量
                $arg_array['mapID'] = $commHandler->generate_seqno('seqno_wechatmap');

                $wecaht_event_matetial_map->mapID = $arg_array['mapID'];

                $wecaht_event_matetial_map->creator = $arg_array['operator'];
            }

            //检查排期是否冲突
            $temp_array['eventID'] = $arg_array['eventID'];
            $temp_array['mapID'] = $arg_array['mapID'];
            $temp_array['startDate'] = $arg_array['startDate'];
            $temp_array['endDate'] = $arg_array['endDate'];
            $checkResult = $this->checkSystemRepeatDate( $temp_array );
            if ( $checkResult['code'] == 200 && $checkResult['data'] == 1 ) {
                throw new Exception('当前时间段已有其他回复内容', 404);
            }

            //保存(更新)素材
            $wechat_material = new entity('wechat_material');
            if( $arg_array['materialID'] > 0 ){

                $wechat_material->materialID = $arg_array['materialID'];
                if (!$this->dbca->fetch($wechat_material)) {
                    throw new Exception('回复内容信息没有找到', 404);
                }

                //若上传了新的媒体文件，则更新媒体文件上传时间
                if( $wechat_material->media_id != $arg_array['media_id'] ){
                    $wechat_material->media_time = date('Y-m-d H:i:s');
                }

            } else {
                $wechat_material->creator = $arg_array['operator'];
                $wechat_material->media_time = date('Y-m-d H:i:s');
            }

            $wechat_material->materialType  = $arg_array['eventType'];
            $wechat_material->materialTitle = isset($arg_array['title'])?$arg_array['title']:'';
            $wechat_material->picLink       = $arg_array['materialLink'];
            $wechat_material->description   = $arg_array['summary'];
            $wechat_material->link          = '';
            $wechat_material->article_id    = '';
            $wechat_material->media_id      = $arg_array['media_id'];
            $this->dbca->save($wechat_material);

            if( $arg_array['materialID'] == 0 ){
                $arg_array['materialID'] = $this->dbca->insert_id;
            }

            $wecaht_event_matetial_map->materialID = $arg_array['materialID'];
            $wecaht_event_matetial_map->eventName = $arg_array['eventName'];
            $wecaht_event_matetial_map->eventType = $arg_array['eventType'];
            $wecaht_event_matetial_map->startDate  = $arg_array['startDate'];
            $wecaht_event_matetial_map->endDate    = $arg_array['endDate'];

            $this->dbca->save( $wecaht_event_matetial_map );

            //提交事务
            $this->dbca->commit();

            return array( 'code'=> 200 , 'message' => '保存成功', 'data' => $arg_array['mapID'] );

        }catch (Exception $e){

            //回滚事务
            $this->dbca->rollBack();

            if( $e->getCode() > 0 ){

                return array( 'code'=>$e->getCode() , 'message'=>$e->getMessage() );

            } else {

                error_log( $e->getMessage() );
                return array( 'code'=>500 , 'message'=>$e->getMessage() );

            }

        }

    }

    /**
     * 保存系统事件多图文回复
     */
    public function saveSystemMoreNews( $arg_array ){

        if( !isset( $arg_array['eventID'],$arg_array['eventName'],$arg_array['startDate'], $arg_array['endDate'])) {
            return array( 'code'=>400 , 'message'=>'参数错误');
        }

        if( !is_numeric( $arg_array['eventID'] ) ){
            return array( 'code'=>400 , 'message'=>'参数错误');
        }

        if( empty( $arg_array['startDate'] ) ){
            return array( 'code'=>400 , 'message'=>'开始时间不能为空');
        }

        if( empty( $arg_array['endDate'] ) ){
            return array( 'code'=>400 , 'message'=>'结束时间不能为空');
        }

        if( $arg_array['startDate'] > $arg_array['endDate'] ){
            return array( 'code'=>400 , 'message'=>'开始时间不能大于结束时间');
        }

        if( empty($arg_array['subArray']) || !is_array($arg_array['subArray']) ){
            return array( 'code'=>400 , 'message'=>'多图文最少需要两条信息');
        } else {

            if( count($arg_array['subArray']) < 2 ){
                return array( 'code'=>400 , 'message'=>'多图文最少需要两条信息');
            }

        }

        if (!isset($arg_array['mapID']) || !is_numeric($arg_array['mapID']) || $arg_array['mapID'] <= 0) {
            $arg_array['mapID'] = 0;
        }

        try{

            //开启事务
            $this->dbca->beginTransaction();

            //保存(更新)关键词映射
            $wecaht_event_matetial_map = new entity('wecaht_event_matetial_map');
            $wecaht_event_matetial_map->eventID = $arg_array['eventID'];
            if( $arg_array['mapID'] > 0 ){

                $wecaht_event_matetial_map->mapID = $arg_array['mapID'];
                if (!$this->dbca->fetch($wecaht_event_matetial_map)) {
                    throw new Exception('回复内容信息没有找到', 404);
                }

            } else {

                //实例化公共类
                $commHandler = new commHandler($this->dbca);

                //获取映射ID自增量
                $arg_array['mapID'] = $commHandler->generate_seqno('seqno_wechatmap');

                $wecaht_event_matetial_map->mapID = $arg_array['mapID'];

                $wecaht_event_matetial_map->creator = $arg_array['operator'];
            }

            //检查排期是否冲突
            $temp_array['eventID'] = $arg_array['eventID'];
            $temp_array['mapID'] = $arg_array['mapID'];
            $temp_array['startDate'] = $arg_array['startDate'];
            $temp_array['endDate'] = $arg_array['endDate'];
            $checkResult = $this->checkSystemRepeatDate( $temp_array );
            if ( $checkResult['code'] == 200 && $checkResult['data'] == 1 ) {
                throw new Exception('当前时间段已有其他回复内容', 404);
            }

            $wecaht_event_matetial_map->eventName = $arg_array['eventName'];
            $wecaht_event_matetial_map->eventType = $arg_array['eventType'];
            $wecaht_event_matetial_map->materialID = $arg_array['subArray'][0];
            $wecaht_event_matetial_map->startDate  = $arg_array['startDate'];
            $wecaht_event_matetial_map->endDate    = $arg_array['endDate'];
            $wecaht_event_matetial_map->isHost     = 1;

            $this->dbca->save( $wecaht_event_matetial_map );

            //删除该排期ID下的映射信息
            $delete_map = 'DELETE FROM wechat_news_map WHERE mapID=?';
            $this->dbca->stmt_query( $delete_map , 'i' , $arg_array['mapID'] );

            //保存映射信息
            foreach ( $arg_array['subArray'] as $key=>$materialID ) {

                //查询素材信息
                $materialInfo = new entity('wechat_material');
                $materialInfo->materialID = $materialID;
                if( !$this->dbca->fetch( $materialInfo ) ){
                    throw new Exception('图文信息有误' , 404);
                }

                if( $materialInfo->link == '' && empty($materialInfo->article_id) ){

                    if( $key == 0 ){
                        $err_msg = '主图文正文不能为空';
                    } else {
                        $err_msg = '第'.$key.'行子图文正文不能为空';
                    }

                    throw new Exception($err_msg , 404);
                }

                //多图文映射表
                $wechat_news_map = new entity('wechat_news_map');
                $wechat_news_map->mapID = $arg_array['mapID'];
                $wechat_news_map->materialID = $materialID;
                $wechat_news_map->sortOrder = $key+1;

                $this->dbca->save($wechat_news_map);

            }

            //提交事务
            $this->dbca->commit();

            return array( 'code'=> 200 , 'message' => '保存成功', 'data' => $arg_array['mapID'] );

        }catch (Exception $e){

            //回滚事务
            $this->dbca->rollBack();

            if( $e->getCode() > 0 ){

                return array( 'code'=>$e->getCode() , 'message'=>$e->getMessage() );

            } else {

                error_log( $e->getMessage() );
                return array( 'code'=>500 , 'message'=>$e->getMessage() );

            }

        }

    }

    /**
     * 保存系统事件单图文回复
     */
    public function saveSystemEventOneNews( $arg_array ){

        quanli_include('module/base/fileDirHandler.class.php');

        //实例化类
        $fileDirHandler = new fileDirHandler();

        //实例公共类
        $commHandler = new commHandler();

        if( !isset( $arg_array['eventID'],$arg_array['eventName'],$arg_array['eventType'], $arg_array['title'], $arg_array['picLink'], $arg_array['startDate'], $arg_array['endDate'], $arg_array['link'], $arg_array['description'], $arg_array['summary'] )) {
            return array( 'code'=>400 , 'message'=>'参数错误');
        }
        if (!is_numeric($arg_array['eventID'])) {
            return array( 'code'=>400 , 'message'=>'参数错误');
        }

        if( !in_array( $arg_array['eventType'] , array(1,2) ) ){
            return array( 'code'=>400 , 'message'=>'参数错误');
        }

        if (empty($arg_array['title'])) {
            return array( 'code'=>400 , 'message'=>'标题不能为空');
        }
        if (empty($arg_array['picLink'])) {
            return array( 'code'=>400 , 'message'=>'请上传图片');
        }
        if (!$commHandler->isDate($arg_array['startDate'])) {
            return array( 'code'=>400 , 'message'=>'开始时间不能为空');
        }
        if (!$commHandler->isDate($arg_array['endDate'])) {
            return array( 'code'=>400 , 'message'=>'结束时间不能为空');
        }
        if ($arg_array['startDate'] > $arg_array['endDate']) {
            return array( 'code'=>400 , 'message'=>'开始时间不能大于结束时间');
        }

        if ( !empty($arg_array['link']) ) {
            $arg_array['description'] = null;
        } else {
            if (empty($arg_array['description'])) {
                return array( 'code'=>400 , 'message'=>'正文内容不能为空');
            }
            $arg_array['link'] = null;
        }

        if (!isset($arg_array['mapID']) || !is_numeric($arg_array['mapID']) || $arg_array['mapID'] <= 0) {
            $arg_array['mapID'] = 0;
        }

        if (!isset($arg_array['materialID']) || !is_numeric($arg_array['materialID']) || $arg_array['materialID'] <= 0) {
            $arg_array['materialID'] = 0;
        }

        try {

            //保存(更新)系统事件映射
            $wechat_event_material_map = new entity('wecaht_event_matetial_map');
            $wechat_event_material_map->eventID = $arg_array['eventID'];
            if( $arg_array['mapID'] > 0 ){

                $wechat_event_material_map->mapID = $arg_array['mapID'];
                if (!$this->dbca->fetch($wechat_event_material_map)) {
                    throw new Exception('回复内容信息没有找到', 404);
                }

            } else {

                //实例化公共类
                $commHandler = new commHandler($this->dbca);

                //获取映射ID自增量
                $arg_array['mapID'] = $commHandler->generate_seqno('seqno_wechatmap');

                $wechat_event_material_map->mapID = $arg_array['mapID'];

                $wechat_event_material_map->creator = $arg_array['operator'];
            }

            //检查排期是否冲突
            $temp_array['eventID'] = $arg_array['eventID'];
            $temp_array['mapID'] = $arg_array['mapID'];
            $temp_array['startDate'] = $arg_array['startDate'];
            $temp_array['endDate'] = $arg_array['endDate'];
            $checkResult = $this->checkSystemRepeatDate( $temp_array );
            if ( $checkResult['code'] == 200 && $checkResult['data'] == 1 ) {
                throw new Exception('当前时间段已有其他回复内容', 404);
            }


            //如果链接为空，则保存模板内容
            if ( empty($arg_array['link']) && $arg_array['selectedFlg'] == 0 ) {

                $temp_array = array(
                    'creator' => $arg_array['operator'],
                    'article_id' => $arg_array['cmsID'],
                    'article_title' => $arg_array['title'],
                    'code_type' => $arg_array['code_type'],
                    'activeType' => $arg_array['activeType'],
                    'code_startDate' => $arg_array['code_startDate'],
                    'code_endDate' => $arg_array['code_endDate'],
                    'use_startDate' => $arg_array['use_startDate'],
                    'use_endDate' => $arg_array['use_endDate'],
                    'limit_num' => $arg_array['limit_num'],
                    'useType' => $arg_array['useType'],
                    'useTime' => $arg_array['useTime'],
                    'article_summary' => $arg_array['summary'],
                    'description' => $arg_array['description'],
                    'promotionID' => $arg_array['promotionID'],
                    'category_id' => 6
                );
                $article_array = $this->saveArticleInfo( $temp_array );
                if ($article_array['code'] != 200) {
                    throw new Exception($article_array['message'], 404);
                }
                $arg_array['article_id'] = $article_array['data'];
            }

            //页面“选择”模板
            if( $arg_array['cmsID'] > 0 &&  $arg_array['selectedFlg'] == 1){
                $arg_array['article_id'] = $arg_array['cmsID'];
            }

            //存在链接时，清空模板ID
            if( !empty( $arg_array['link'] ) || ( empty($arg_array['cmsID']) && !isset($arg_array['article_id']) ) ){
                $arg_array['article_id'] = NULL;
            }

            //保存(更新)素材
            $wechat_material = new entity('wechat_material');
            if( $arg_array['materialID'] > 0 ){

                $wechat_material->materialID = $arg_array['materialID'];
                if (!$this->dbca->fetch($wechat_material)) {
                    throw new Exception('回复内容信息没有找到', 404);
                }

            } else {
                $wechat_material->creator = $arg_array['operator'];
            }

            //将图片路径打成数组
            $picture_array = explode( '/' , $arg_array['picLink'] );

            //转移图片路径
            if( $picture_array[0] == '' || $picture_array[1] == 'quanliadmin' ){

                if( ($arg_array['mapID'] &&  $arg_array['picLink'] != $wechat_material->picLink) || empty($arg_array['mapID']) ){

                    $oldName = G_APPLICATION_BASEPATH . $arg_array['picLink'];
                    $newName = G_IMAGE_SAVE_ROOT . 'wechat/cotent/' . $fileDirHandler->basename($oldName);

                    if (!$fileDirHandler->move($oldName, $newName)) {
                        throw new Exception('文件移动失败', 404);
                    }

                    $arg_array['picLink'] = 'wechat/cotent/' . $fileDirHandler->basename($oldName);

                }

            }

            $wechat_material->materialType = $arg_array['eventType'];
            $wechat_material->materialTitle = $arg_array['title'];
            $wechat_material->link = $arg_array['link'];
            $wechat_material->picLink = $arg_array['picLink'];
            $wechat_material->description = $arg_array['summary'];
            $wechat_material->article_id = $arg_array['article_id'];
            $this->dbca->save($wechat_material);

            if( $arg_array['materialID'] == 0 ){
                $arg_array['materialID'] = $this->dbca->insert_id;
            }

            //保存(更新)映射表信息
            $wechat_event_material_map->eventName = $arg_array['eventName'];
            $wechat_event_material_map->eventType = $arg_array['eventType'];
            $wechat_event_material_map->materialID = $arg_array['materialID'];
            $wechat_event_material_map->startDate = $arg_array['startDate'];
            $wechat_event_material_map->endDate = $arg_array['endDate'];

            //保存映射表信息
            $this->dbca->save( $wechat_event_material_map );

            return array( 'code'=> 200 , 'message' => '保存成功', 'data' => $arg_array['mapID'] );

        } catch (Exception $e){

            if( $e->getCode() > 0 ){

                return array( 'code'=>$e->getCode() , 'message'=>$e->getMessage() );

            } else {

                error_log( $e->getMessage() );
                return array( 'code'=>500 , 'message'=>$e->getMessage() );

            }

        }

    }

    /**
     * 保存系统事件文本回复
     */
    public function saveSystemEventText( $arg_array ){

        if( !isset( $arg_array['eventID'],$arg_array['eventName'],$arg_array['eventType'], $arg_array['content'],  $arg_array['startDate'], $arg_array['endDate'], $arg_array['link'], $arg_array['description'], $arg_array['summary'] )) {
            return array( 'code'=>400 , 'message'=>'参数错误');
        }

        if( !is_numeric( $arg_array['eventID'] ) ){
            return array( 'code'=>400 , 'message'=>'参数错误');
        }

        if( !in_array( $arg_array['eventType'] , array(1,2) ) ){
            return array( 'code'=>400 , 'message'=>'参数错误');
        }

        if( empty( $arg_array['content'] ) ){
            return array( 'code'=>400 , 'message'=>'请输入文本内容');
        }

        if( empty( $arg_array['startDate'] ) ){
            return array( 'code'=>400 , 'message'=>'开始时间不能为空');
        }

        if( empty( $arg_array['endDate'] ) ){
            return array( 'code'=>400 , 'message'=>'结束时间不能为空');
        }

        if( $arg_array['startDate'] > $arg_array['endDate'] ){
            return array( 'code'=>400 , 'message'=>'开始时间不能大于结束时间');
        }

        if( !empty($arg_array['link']) ){

            $arg_array['description'] = NULL;

        } else {

            if( !empty($arg_array['description']) ){

                if( empty( $arg_array['title'] ) ){
                    return array( 'code'=>400 , 'message'=>'标题不能为空');
                }

                $arg_array['link'] = NULL;

            }

        }

        if (!isset($arg_array['mapID']) || !is_numeric($arg_array['mapID']) || $arg_array['mapID'] <= 0) {
            $arg_array['mapID'] = 0;
        }

        if (!isset($arg_array['materialID']) || !is_numeric($arg_array['materialID']) || $arg_array['materialID'] <= 0) {
            $arg_array['materialID'] = 0;
        }

        try{

            //保存(更新)映射表
            $wechat_event_material_map = new entity('wecaht_event_matetial_map');
            $wechat_event_material_map->eventID = $arg_array['eventID'];
            if( $arg_array['mapID'] > 0 ){

                $wechat_event_material_map->mapID = $arg_array['mapID'];
                if (!$this->dbca->fetch($wechat_event_material_map)) {
                    throw new Exception('回复内容信息没有找到', 404);
                }

            } else {

                //实例化公共类
                $commHandler = new commHandler($this->dbca);

                //获取映射ID自增量
                $arg_array['mapID'] = $commHandler->generate_seqno('seqno_wechatmap');

                $wechat_event_material_map->mapID = $arg_array['mapID'];

                $wechat_event_material_map->creator = $arg_array['operator'];
            }

            //检查排期是否冲突
            $temp_array['eventID'] = $arg_array['eventID'];
            $temp_array['mapID'] = $arg_array['mapID'];
            $temp_array['startDate'] = $arg_array['startDate'];
            $temp_array['endDate'] = $arg_array['endDate'];
            $checkResult = $this->checkSystemRepeatDate( $temp_array );
            if ( $checkResult['code'] == 200 && $checkResult['data'] == 1 ) {
                throw new Exception('当前时间段已有其他回复内容', 404);
            }

            //如果链接为空,正文不为空,且为新增的模板，则保存模板
            if( empty($arg_array['link']) && !empty( $arg_array['description'] ) && $arg_array['selectedFlg'] == 0 ){

                $temp_array = array(
                    'creator' => $arg_array['operator'],
                    'article_id' => $arg_array['cmsID'],
                    'article_title' => $arg_array['title'],
                    'code_type' => $arg_array['code_type'],
                    'activeType' => $arg_array['activeType'],
                    'code_startDate' => $arg_array['code_startDate'],
                    'code_endDate' => $arg_array['code_endDate'],
                    'use_startDate' => $arg_array['use_startDate'],
                    'use_endDate' => $arg_array['use_endDate'],
                    'limit_num' => $arg_array['limit_num'],
                    'useType' => $arg_array['useType'],
                    'useTime' => $arg_array['useTime'],
                    'article_summary' => $arg_array['summary'],
                    'description' => $arg_array['description'],
                    'promotionID' => $arg_array['promotionID'],
                    'category_id' => 6
                );

                $article_array = $this->saveArticleInfo( $temp_array );
                if ($article_array['code'] != 200) {
                    throw new Exception($article_array['message'], 404);
                }
                $arg_array['article_id'] = $article_array['data'];

            }

            //页面“选择”模板
            if( $arg_array['cmsID'] > 0 &&  $arg_array['selectedFlg'] == 1){
                $arg_array['article_id'] = $arg_array['cmsID'];
            }

            //存在链接时，清空模板ID
            if( !empty( $arg_array['link'] ) || ( empty($arg_array['cmsID']) && !isset($arg_array['article_id']) ) ){
                $arg_array['article_id'] = NULL;
            }

            //保存(更新)素材
            $wechat_material = new entity('wechat_material');
            if( $arg_array['materialID'] > 0 ){

                $wechat_material->materialID = $arg_array['materialID'];
                if (!$this->dbca->fetch($wechat_material)) {
                    throw new Exception('回复内容信息没有找到', 404);
                }

            } else {
                $wechat_material->creator = $arg_array['operator'];
            }

            $wechat_material->materialType = $arg_array['eventType'];
            $wechat_material->materialTitle = $arg_array['title'];
            $wechat_material->description = $arg_array['content'];
            $wechat_material->link = $arg_array['link'];
            $wechat_material->article_id = $arg_array['article_id'];
            $this->dbca->save($wechat_material);

            if( $arg_array['materialID'] == 0 ){
                $arg_array['materialID'] = $this->dbca->insert_id;
            }

            //保存(更新)映射表信息
            $wechat_event_material_map->eventName = $arg_array['eventName'];
            $wechat_event_material_map->eventType = $arg_array['eventType'];
            $wechat_event_material_map->materialID = $arg_array['materialID'];
            $wechat_event_material_map->startDate = $arg_array['startDate'];
            $wechat_event_material_map->endDate = $arg_array['endDate'];

            //保存映射表信息
            $this->dbca->save( $wechat_event_material_map );

            return array( 'code'=> 200 , 'message' => '保存成功', 'data' => $arg_array['mapID'] );

        }catch ( Exception $e ){

            if( $e->getCode() > 0 ){

                return array( 'code'=>$e->getCode() , 'message'=>$e->getMessage() );

            } else {

                error_log( $e->getMessage() );
                return array( 'code'=>500 , 'message'=>$e->getMessage() );

            }

        }

    }

    /**
     * 删除系统事件排期
     */
    function deleteSystemEventDate( $arg_array ){

        if( !isset( $arg_array['eventID'] , $arg_array['mapID']) || !is_numeric($arg_array['eventID']) || !is_numeric($arg_array['mapID']) ){
            return array( 'code'=>400 , 'message'=>'参数错误' );
        }

        try{

            //查询关键词排期信息
            $map_obj = new entity('wecaht_event_matetial_map');
            $map_obj->mapID = $arg_array['mapID'];
            $map_obj->eventID = $arg_array['eventID'];

            if( !$this->dbca->fetch( $map_obj ) ){
                throw new Exception( '排期回复信息没找到' , 404 );
            }

            //删除
            $this->dbca->delete( $map_obj );

            return array( 'code'=>200 , 'message'=>'删除成功' , 'data'=>$arg_array['mapID'] );

        }catch (Exception $e){

            if( $e->getCode() > 0 ){

                return array( 'code'=>$e->getCode() , 'message'=>$e->getMessage() );

            } else {

                error_log( $e->getMessage() );
                return array( 'code'=>500 , 'message'=>$e->getMessage() );

            }

        }

    }

    /**
     * 查询菜单信息
     * @param array $arg_array 查询参数数组
     * $arg_array = array (
     *      'sortname' => string 排序字段
     *      'sortorder' => string 排序方式
     *      'page' => int 分页页码
     *      'rp' => int 分页页数
     * )
     * @return null
     */
    public function searchMenuList( &$arg_array ) {

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //菜单ID
        if ( isset($arg_array['menuID']) && is_numeric($arg_array['menuID']) ) {
            $sql .= ' AND menuID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['menuID'];
        }

        //菜单名称
        if ( isset($arg_array['menuName']) && !empty($arg_array['menuName']) ) {
            $sql .= ' AND menuName = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['menuName'];
        }

        //菜单类型
        if ( isset($arg_array['menuType']) && in_array($arg_array['menuType'], array(1, 2)) ) {
            $sql .= ' AND menuType = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['menuType'];
        }

        //菜单键值
        if ( isset($arg_array['key']) && !empty($arg_array['key']) ) {
            $sql .= ' AND key = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['key'];
        }

        //菜单等级
        if ( isset($arg_array['level']) && in_array($arg_array['level'], array(1, 2)) ) {
            $sql .= ' AND level = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['level'];
        }

        //父级菜单ID
        if ( isset($arg_array['parentID']) && is_numeric($arg_array['parentID']) ) {
            $sql .= ' AND parentID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['parentID'];
        }

        //位置
        if ( isset($arg_array['position']) && is_numeric($arg_array['position']) ) {
            $sql .= ' AND position = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['position'];
        }

        //子菜单位置
        if ( isset($arg_array['subPosition']) && is_numeric($arg_array['subPosition']) ) {
            $sql .= ' AND subPosition = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['subPosition'];
        }

        if( !empty( $arg_array['extendSql'] ) ){
            $sql .= $arg_array['extendSql'];
        }

        if ( $sql ) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if ( isset($arg_array['rp']) && $arg_array['rp'] > 1 ) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM wechat_menuConfig ' . $sql;

                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if ( isset($arg_array['sortname']) && !empty($arg_array['sortname']) )
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if ( !isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0 )
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if ( isset($arg_array['sortname']) && !empty($arg_array['sortname']) )
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询分类信息
            $search_sql = 'SELECT * FROM wechat_menuConfig ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            foreach($temp_item_array as &$item) {

                //菜单类型
                $menuTypeName = '';

                if ( $item->menuType == 1 ) {
                    $menuTypeName = 'view';
                } else if ( $item->menuType == 2 ) {
                    $menuTypeName = 'click';
                }

                $item_array[] = array(
                    'menuID' 	  => $item->menuID,
                    'menuName' 	  => $item->menuName,
                    'menuType' 	  => $item->menuType,
                    'position' 	  => $item->position,
                    'subPosition' 	  => $item->subPosition,
                    'menuTypeName'   => $menuTypeName,
                    'keyValue' => $item->keyValue,
                    'url'      => $item->url,
                    'level' 	  => $item->level,
                    'parentID' 	  => $item->parentID
                );

            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }

    /**
     * 保存菜单信息
     */
    function saveMenu( $arg_array ){

        if( !isset( $arg_array['menuName'] , $arg_array['position'] , $arg_array['menuType'] ) ){
            return array( 'code'=>400 , 'message'=>'参数错误');
        }

        if( !in_array( $arg_array['menuType'] , array(1,2,3) ) ){
            return array( 'code'=>400 , 'message'=>'菜单类型错误');
        }

        if( $arg_array['menuType'] == 1 ){  //如果菜单类型为“view”

            $arg_array['keyValue'] = '';

        } else if ( $arg_array['menuType'] == 2 ){   //如果菜单类型为“click”

            $arg_array['url'] = '';

        }

        if (!isset($arg_array['menuID']) || !is_numeric($arg_array['menuID']) || $arg_array['menuID'] <= 0) {
            $arg_array['menuID'] = 0;
        }

        if (!isset($arg_array['parentID']) || !is_numeric($arg_array['parentID']) || $arg_array['parentID'] <= 0) {
            $arg_array['parentID'] = 0;
        }

        //记录一级菜单子菜单信息
        $sub_array = array();

        try{

            //开启事务
            $this->dbca->beginTransaction();

            //菜单为二级菜单
            if( $arg_array['parentID'] > 0 ){

                //查询一级菜单信息
                $first_menu = new entity('wechat_menuConfig');
                $first_menu->menuID = $arg_array['parentID'];

                if( !$this->dbca->fetch( $first_menu ) ){
                    throw new Exception( '没有找到一级菜单信息' , 404 );
                }

                $first_menu->menuType = 3;
                $first_menu->keyValue = '';
                $first_menu->url = '';
                $first_menu->level = 1;
                $first_menu->parentID = 0;

                //删除一级菜单所有的排期
                $delete_sql = 'DELETE FROM wechat_menu_material_map WHERE menuID=?';
                $this->dbca->stmt_query( $delete_sql , 'i' , $arg_array['parentID'] );

                $this->dbca->save( $first_menu );

            }

            //菜单修改为一级菜单
            if( $arg_array['parentID'] == 0 && $arg_array['menuID'] > 0 && in_array( $arg_array['menuType'] , array(1,2) ) ){

                //查询该一级菜单下所有的子菜单
                $select_sub_sql = 'SELECT * FROM wechat_menuConfig WHERE parentID=?';
                $get_sub        = $this->dbca->stmt_query( $select_sub_sql , 'i' , $arg_array['menuID']);

                if( $get_sub ){

                    foreach( $get_sub as $sub ){
                        $sub_array[] = $sub->menuID;
                    }

                }

                /**
                 * 删除该一级菜单下的所有子菜单
                 * 因为菜单表和映射表之间存在外键（menuID）,所以删除菜单时，映射表中的信息也会被删除
                 */
                $delete_sql = 'DELETE FROM wechat_menuConfig WHERE parentID=?';
                $this->dbca->stmt_query( $delete_sql , 'i' , $arg_array['menuID'] );

            }

            //保存菜单
            $menu_obj = new entity('wechat_menuConfig');

            if( $arg_array['menuID'] > 0 ){

                $menu_obj->menuID = $arg_array['menuID'];

                if( !$this->dbca->fetch( $menu_obj ) ){
                    throw new Exception( '没有找到菜单信息' , 404 );
                }

                //如果修改时保存类型为“view”，则删除排期信息
                if( $arg_array['menuType'] == 1 ){

                    //删除排期
                    $delete_paiqi = 'DELETE FROM wechat_menu_material_map WHERE menuID=?';
                    $this->dbca->stmt_query( $delete_paiqi , 'i' , $arg_array['menuID'] );
                    
                     $menu_obj->keyValue = '';

                }
                
                //如果菜单类型修改为“CLICK事件”
                if( $arg_array['menuType'] == 2 ){

	                $key_value = 'MENU_'.$arg_array['menuID'];
	                
	                $menu_obj->keyValue = $key_value;
                	
                }
                
            } else {

                $menu_obj->creator = $arg_array['operator'];

                //如果菜单类型为“消息”类型
                if( $arg_array['menuType'] == 2 ){

                    //查询数据库中最大的ID值加一
                    $select_max_id = 'SELECT MAX(menuID)+1 as maxID FROM wechat_menuConfig';
                    $getMax        = $this->dbca->stmt_query( $select_max_id );

                    if( empty($getMax) || empty($getMax[0]) ){
                        $maxID = 1;
                    } else {
                        $maxID = $getMax[0]->maxID;
                    }

                    $key_value = 'MENU_'.$maxID;

                    $menu_obj->keyValue = $key_value;

                } else {

                    $menu_obj->keyValue = '';

                }

            }

            $menu_obj->menuName = $arg_array['menuName'];
            $menu_obj->position = $arg_array['position'];
            $menu_obj->subPosition = isset($arg_array['subPosition'])?$arg_array['subPosition']:'';
            $menu_obj->menuType = $arg_array['menuType'];
            $menu_obj->url = isset($arg_array['url'])?$arg_array['url']:'';
            $menu_obj->level = $arg_array['level'];
            $menu_obj->parentID = $arg_array['parentID'];

            $this->dbca->save( $menu_obj );

            if( $arg_array['menuID'] == 0 ){
                $arg_array['menuID'] = $this->dbca->insert_id;
            }

            //提交事务
            $this->dbca->commit();

            return array( 'code'=>200 , 'message'=>'保存成功' , 'data'=>$arg_array['menuID'] , 'sub'=>$sub_array );

        }catch (Exception $e ){

            //回滚事务
            $this->dbca->rollBack();

            if( $e->getCode() > 0 ){

                return array( 'code'=>$e->getCode() , 'message'=>$e->getMessage() );

            } else {

                error_log( $e->getMessage() );
                return array( 'code'=>500 , 'message'=>$e->getMessage() );

            }

        }

    }


    /**
     * 删除菜单
     */
    public function deleteMenu( $arg_array , $G_PGLOB ){

        if( !isset( $arg_array['menuID']) || !is_numeric($arg_array['menuID']) ){
            return array( 'code'=>400 , 'message'=>'参数错误');
        }

        //记录一级菜单子菜单ID的数组
        $sub_array = array();

        try{

            //开启事务
            $this->dbca->beginTransaction();

            //查询菜单信息
            $map_obj = new entity('wechat_menuConfig');
            $map_obj->menuID = $arg_array['menuID'];

            if( !$this->dbca->fetch( $map_obj ) ){
                throw new Exception( '没有找到菜单信息' , 404 );
            }

            //如果删除一级菜单，则同时删除二级菜单所有信息
            if( $map_obj->level == 1 ){

                //查询该一级菜单下所有的子菜单
                $select_sub_sql = 'SELECT * FROM wechat_menuConfig WHERE parentID=?';
                $get_sub        = $this->dbca->stmt_query( $select_sub_sql , 'i' , $arg_array['menuID']);

                if( $get_sub ){

                    foreach( $get_sub as $sub ){
                        $sub_array[] = $sub->menuID;
                    }

                }

                /**
                 * 删除该一级菜单下的所有子菜单
                 * 因为菜单表和映射表之间存在外键（menuID）,所以删除菜单时，映射表中的信息也会被删除
                 */
                $delete_sql = 'DELETE FROM wechat_menuConfig WHERE parentID=?';
                $this->dbca->stmt_query( $delete_sql , 'i' , $arg_array['menuID'] );

            }

            //删除
            $this->dbca->delete( $map_obj );

            //提交事务
            $this->dbca->commit();

            //实例化微信接口类
            $wechatAdvancedInterface = new wechatAdvancedInterface($G_PGLOB);

            if( isset($arg_array['last']) && $arg_array['last'] == 1 ){  //标志为删除的菜单是最后一个一级菜单

                //调用菜单删除接口，同步菜单数据
                $interface_return = $wechatAdvancedInterface->deleteCustomizingMenu();

                if( $interface_return['code'] != 200 ){
                    throw new Exception( '菜单信息同步失败' , $interface_return['code'] );
                }

            }

            return array( 'code'=>200 , 'message'=>'删除成功' , 'data'=>$arg_array['menuID'] , 'sub'=>$sub_array );

        }catch (Exception $e){

            //回滚事务
            $this->dbca->rollBack();

            if( $e->getCode() > 0 ){

                return array( 'code'=>$e->getCode() , 'message'=>$e->getMessage() );

            } else {

                error_log( $e->getMessage() );
                return array( 'code'=>500 , 'message'=>$e->getMessage() );

            }

        }

    }

    /**
     * 菜单回复内容列表
     */
    function searchMenuReplyList( $arg_array ){

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //内容ID
        if ( isset($arg_array['mapID']) && is_numeric($arg_array['mapID']) ) {
            $sql .= ' AND wmmm.mapID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['mapID'];
        }

        //关键词ID
        if ( isset($arg_array['menuID']) && is_numeric($arg_array['menuID']) ) {
            $sql .= ' AND wmmm.menuID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['menuID'];
        }

        //素材ID
        if ( isset($arg_array['materialID']) && is_numeric($arg_array['materialID']) ) {
            $sql .= ' AND wmmm.materialID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['materialID'];
        }

        //有效期开始日期
        if ( isset($arg_array['startDate']) && !empty($arg_array['startDate']) ) {
            $sql .= ' AND wmmm.startDate <= ?';
            $params_type .= 's';
            $params_array[] = $arg_array['startDate'];
        }

        //有效期结束日期
        if ( isset($arg_array['endDate']) && !empty($arg_array['endDate']) ) {
            $sql .= ' AND wmmm.endDate >= ?';
            $params_type .= 's';
            $params_array[] = $arg_array['endDate'];
        }

        //是否是主图片
        if ( isset($arg_array['isHost']) && in_array( $arg_array['isHost'] , array(0,1) ) ) {
            $sql .= ' AND wmmm.isHost = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['isHost'];
        }

        if( !empty( $arg_array['extendSql'] ) ){
            $sql .= $arg_array['extendSql'];
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count
                            FROM wechat_menu_material_map wmmm
                            INNER JOIN wechat_material wm ON wmmm.materialID = wm.materialID ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询信息
            $search_sql = 'SELECT wmmm.mapID,wmmm.menuID,wmmm.startDate,wmmm.endDate,wmmm.isHost,
                        wm.materialID,wm.materialType,wm.materialTitle,wm.picLink,wm.description,wm.link,wm.article_id,wm.timeStamp,wm.createTime,
                        wm.media_id,wm.media_time
                        FROM wechat_menu_material_map wmmm
                        INNER JOIN wechat_material wm ON wmmm.materialID = wm.materialID ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            foreach($temp_item_array as &$item) {
                $item_array[] = array(
                    'timeStamp'  => $item->timeStamp,
                    'createTime'  => $item->createTime,
                    'mapID'  => $item->mapID,
                    'menuID'=> $item->menuID,
                    'startDate' => $item->startDate,
                    'endDate' => $item->endDate,
                    'startTime' => date('Y-m-d' , strtotime($item->startDate)),
                    'endTime' => date('Y-m-d' , strtotime($item->endDate)),
                    'isHost' => $item->isHost,
                    'materialID' => $item->materialID,
                    'materialType' => $item->materialType,
                    'materialTitle' => $item->materialTitle,
                    'picLinkShow' => empty($item->picLink) ? '' : G_IMAGE_URL.$item->picLink,
                    'picLink' => $item->picLink,
                    'description' => $item->description,
                    'link' => $item->link,
                    'article_id' => $item->article_id,
                    'media_id' => $item->media_id,
                    'media_time' => $item->media_time
                );

            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;


        }

    }

    /**
     * 检查菜单回复内容排期是否重复
     * $menuID  菜单ID
     * $mapID  内容ID
     */
    public function checkMenuRepeatDate( $arg_array ){

        if( !isset( $arg_array['menuID'] ) || !is_numeric( $arg_array['menuID'] ) || empty( $arg_array['menuID'] ) ){
            return array( 'code'=>400 , '缺少参数' );
        }

        if( empty( $arg_array['startDate'] ) || empty( $arg_array['endDate'] ) ){
            return array( 'code'=>400 , '缺少参数' );
        }

        //查询SQL
        $sql = ' SELECT * FROM wechat_menu_material_map WHERE menuID=%d AND ( ( startDate <= %s AND endDate >= %s  ) OR ( startDate <= %s AND endDate >= %s ) OR ( startDate >= %s AND endDate <= %s ) ) ';

        //存在mapID时的查询SQL
        $sql_edit = ' SELECT * FROM wechat_menu_material_map WHERE menuID=%d AND mapID <> %d AND ( ( startDate <= %s AND endDate >= %s  ) OR ( startDate <= %s AND endDate >= %s ) OR ( startDate >= %s AND endDate <= %s ) ) ';

        //校验排期是否重复SQL
        if( $arg_array['mapID'] > 0 ){

            $check_sql = sprintf( $sql_edit , $arg_array['menuID'] , $arg_array['mapID'] , '\''.$arg_array['startDate'].'\'' , '\''.$arg_array['startDate'].'\'' , '\''.$arg_array['endDate'].'\'', '\''.$arg_array['endDate'].'\'' , '\''.$arg_array['startDate'].'\'' , '\''.$arg_array['endDate'].'\'');

        } else {

            $check_sql = sprintf( $sql , $arg_array['menuID'] , '\''.$arg_array['startDate'].'\'' , '\''.$arg_array['startDate'].'\'' , '\''.$arg_array['endDate'].'\'', '\''.$arg_array['endDate'].'\'', '\''.$arg_array['startDate'].'\'' , '\''.$arg_array['endDate'].'\'');

        }

        //查询结果
        $result = $this->dbca->stmt_query( $check_sql );

        if( $result ){
            return array( 'code'=>200 , 'data'=>1 );
        } else {
            return array( 'code'=>200 , 'data'=>0 );
        }

    }

    /**
     * 保存菜单多图文回复
     */
    public function saveMenuMoreNewsReply( $arg_array ){

        if( !isset( $arg_array['menuID'],$arg_array['startDate'], $arg_array['endDate'])) {
            return array( 'code'=>400 , 'message'=>'参数错误');
        }

        if( !is_numeric( $arg_array['menuID'] ) ){
            return array( 'code'=>400 , 'message'=>'参数错误');
        }

        if( empty( $arg_array['startDate'] ) ){
            return array( 'code'=>400 , 'message'=>'开始时间不能为空');
        }

        if( empty( $arg_array['endDate'] ) ){
            return array( 'code'=>400 , 'message'=>'结束时间不能为空');
        }

        if( $arg_array['startDate'] > $arg_array['endDate'] ){
            return array( 'code'=>400 , 'message'=>'开始时间不能大于结束时间');
        }

        if( empty($arg_array['subArray']) || !is_array($arg_array['subArray']) ){
            return array( 'code'=>400 , 'message'=>'多图文最少需要两条信息');
        } else {

            if( count($arg_array['subArray']) < 2 ){
                return array( 'code'=>400 , 'message'=>'多图文最少需要两条信息');
            }

        }

        if (!isset($arg_array['mapID']) || !is_numeric($arg_array['mapID']) || $arg_array['mapID'] <= 0) {
            $arg_array['mapID'] = 0;
        }

        try{

            //开启事务
            $this->dbca->beginTransaction();

            //查询菜单信息
            $temp_array = array(
                'menuID' => $arg_array['menuID']
            );
            $menu_array = $this->searchMenuList( $temp_array );
            if (!$menu_array) {
                throw new Exception('菜单信息没有找到', 404);
            }

            //保存(更新)关键词映射
            $wechat_menu_material_map = new entity('wechat_menu_material_map');
            $wechat_menu_material_map->menuID = $arg_array['menuID'];
            if( $arg_array['mapID'] > 0 ){

                $wechat_menu_material_map->mapID = $arg_array['mapID'];
                if (!$this->dbca->fetch($wechat_menu_material_map)) {
                    throw new Exception('回复内容信息没有找到', 404);
                }

            } else {

                //实例化公共类
                $commHandler = new commHandler($this->dbca);

                //获取映射ID自增量
                $arg_array['mapID'] = $commHandler->generate_seqno('seqno_wechatmap');

                $wechat_menu_material_map->mapID = $arg_array['mapID'];

                $wechat_menu_material_map->creator = $arg_array['operator'];
            }

            //检查排期是否冲突
            $temp_array['mapID'] = $arg_array['mapID'];
            $temp_array['startDate'] = $arg_array['startDate'];
            $temp_array['endDate'] = $arg_array['endDate'];
            $checkResult = $this->checkMenuRepeatDate( $temp_array );
            if ( $checkResult['code'] == 200 && $checkResult['data'] == 1 ) {
                throw new Exception('当前时间段已有其他回复内容', 404);
            }

            $wechat_menu_material_map->materialID = $arg_array['subArray'][0];
            $wechat_menu_material_map->startDate  = $arg_array['startDate'];
            $wechat_menu_material_map->endDate    = $arg_array['endDate'];
            $wechat_menu_material_map->isHost     = 1;

            $this->dbca->save( $wechat_menu_material_map );

            //删除该排期ID下的映射信息
            $delete_map = 'DELETE FROM wechat_news_map WHERE mapID=?';
            $this->dbca->stmt_query( $delete_map , 'i' , $arg_array['mapID'] );

            //保存映射信息
            foreach ( $arg_array['subArray'] as $key=>$materialID ) {

                //查询素材信息
                $materialInfo = new entity('wechat_material');
                $materialInfo->materialID = $materialID;
                if( !$this->dbca->fetch( $materialInfo ) ){
                    throw new Exception('图文信息有误' , 404);
                }

                if( $materialInfo->link == '' && empty($materialInfo->article_id) ){

                    if( $key == 0 ){
                        $err_msg = '主图文正文不能为空';
                    } else {
                        $err_msg = '第'.$key.'行子图文正文不能为空';
                    }

                    throw new Exception($err_msg , 404);
                }

                //多图文映射表
                $wechat_news_map = new entity('wechat_news_map');
                $wechat_news_map->mapID = $arg_array['mapID'];
                $wechat_news_map->materialID = $materialID;
                $wechat_news_map->sortOrder = $key+1;

                $this->dbca->save($wechat_news_map);

            }

            //提交事务
            $this->dbca->commit();

            return array( 'code'=> 200 , 'message' => '保存成功', 'data' => $arg_array['mapID'] );

        }catch (Exception $e){

            //回滚事务
            $this->dbca->rollBack();

            if( $e->getCode() > 0 ){

                return array( 'code'=>$e->getCode() , 'message'=>$e->getMessage() );

            } else {

                error_log( $e->getMessage() );
                return array( 'code'=>500 , 'message'=>$e->getMessage() );

            }

        }

    }

    /**
     * 保存菜单事件多媒体回复
     */
    public function saveMenuMediaReply($arg_array){

        if( !isset( $arg_array['menuID'],$arg_array['menuType'],$arg_array['media_id'],$arg_array['materialLink'],$arg_array['startDate'], $arg_array['endDate'])) {
            return array( 'code'=>400 , 'message'=>'参数错误');
        }

        if( !is_numeric( $arg_array['menuID'] ) ){
            return array( 'code'=>400 , 'message'=>'参数错误');
        }

        if( empty( $arg_array['materialLink'] ) ){
            if( $arg_array['menuType'] == 4 ){
                return array( 'code'=>400 , 'message'=>'请上传音频文件');
            } else {
                return array( 'code'=>400 , 'message'=>'请上传视频文件');
            }
        }

        //视频需要填写标题
        if( $arg_array['menuType'] == 5 && empty($arg_array['title']) ){
            return array( 'code'=>400 , 'message'=>'请输入1到64个字的标题');
        }

        if( empty( $arg_array['startDate'] ) ){
            return array( 'code'=>400 , 'message'=>'开始时间不能为空');
        }

        if( empty( $arg_array['endDate'] ) ){
            return array( 'code'=>400 , 'message'=>'结束时间不能为空');
        }

        if( $arg_array['startDate'] > $arg_array['endDate'] ){
            return array( 'code'=>400 , 'message'=>'开始时间不能大于结束时间');
        }

        if (!isset($arg_array['mapID']) || !is_numeric($arg_array['mapID']) || $arg_array['mapID'] <= 0) {
            $arg_array['mapID'] = 0;
        }

        if (!isset($arg_array['materialID']) || !is_numeric($arg_array['materialID']) || $arg_array['materialID'] <= 0) {
            $arg_array['materialID'] = 0;
        }

        if( isset($arg_array['summary']) && !empty($arg_array['summary']) ){
            $arg_array['summary'] = htmlspecialchars($arg_array['summary']);
        } else {
            $arg_array['summary'] = '';
        }

        try{

            //开启事务
            $this->dbca->beginTransaction();

            //查询菜单信息
            $temp_array = array(
                'menuID' => $arg_array['menuID']
            );
            $menu_array = $this->searchMenuList( $temp_array );
            if (!$menu_array) {
                throw new Exception('菜单信息没有找到', 404);
            }

            //保存(更新)菜单映射
            $wechat_menu_material_map = new entity('wechat_menu_material_map');
            $wechat_menu_material_map->menuID = $arg_array['menuID'];
            if( $arg_array['mapID'] > 0 ){

                $wechat_menu_material_map->mapID = $arg_array['mapID'];
                if (!$this->dbca->fetch($wechat_menu_material_map)) {
                    throw new Exception('回复内容信息没有找到', 404);
                }

            } else {

                //实例化公共类
                $commHandler = new commHandler($this->dbca);

                //获取映射ID自增量
                $arg_array['mapID'] = $commHandler->generate_seqno('seqno_wechatmap');

                $wechat_menu_material_map->mapID = $arg_array['mapID'];

                $wechat_menu_material_map->creator = $arg_array['operator'];
            }

            //检查排期是否冲突
            $temp_array['mapID'] = $arg_array['mapID'];
            $temp_array['startDate'] = $arg_array['startDate'];
            $temp_array['endDate'] = $arg_array['endDate'];
            $checkResult = $this->checkMenuRepeatDate( $temp_array );
            if ( $checkResult['code'] == 200 && $checkResult['data'] == 1 ) {
                throw new Exception('当前时间段已有其他回复内容', 404);
            }

            //保存(更新)素材
            $wechat_material = new entity('wechat_material');
            if( $arg_array['materialID'] > 0 ){

                $wechat_material->materialID = $arg_array['materialID'];
                if (!$this->dbca->fetch($wechat_material)) {
                    throw new Exception('回复内容信息没有找到', 404);
                }

                //若上传了新的媒体文件，则更新媒体文件上传时间
                if( $wechat_material->media_id != $arg_array['media_id'] ){
                    $wechat_material->media_time = date('Y-m-d H:i:s');
                }

            } else {
                $wechat_material->creator = $arg_array['operator'];
                $wechat_material->media_time = date('Y-m-d H:i:s');
            }

            $wechat_material->materialType  = $arg_array['menuType'];
            $wechat_material->materialTitle = isset($arg_array['title'])?$arg_array['title']:'';
            $wechat_material->picLink       = $arg_array['materialLink'];
            $wechat_material->description   = $arg_array['summary'];
            $wechat_material->link          = '';
            $wechat_material->article_id    = '';
            $wechat_material->media_id      = $arg_array['media_id'];
            $this->dbca->save($wechat_material);

            if( $arg_array['materialID'] == 0 ){
                $arg_array['materialID'] = $this->dbca->insert_id;
            }

            $wechat_menu_material_map->materialID = $arg_array['materialID'];
            $wechat_menu_material_map->startDate  = $arg_array['startDate'];
            $wechat_menu_material_map->endDate    = $arg_array['endDate'];

            $this->dbca->save( $wechat_menu_material_map );

            //提交事务
            $this->dbca->commit();

            return array( 'code'=> 200 , 'message' => '保存成功', 'data' => $arg_array['mapID'] );

        }catch (Exception $e){

            //回滚事务
            $this->dbca->rollBack();

            if( $e->getCode() > 0 ){

                return array( 'code'=>$e->getCode() , 'message'=>$e->getMessage() );

            } else {

                error_log( $e->getMessage() );
                return array( 'code'=>500 , 'message'=>$e->getMessage() );

            }

        }

    }

    /**
     * 保存菜单单图文回复
     */
    public function saveMenuOneNewsReply( $arg_array ){

        quanli_include('module/base/fileDirHandler.class.php');

        //实例化类
        $fileDirHandler = new fileDirHandler();

        //实例公共类
        $commHandler = new commHandler();

        if( !isset( $arg_array['menuID'], $arg_array['title'], $arg_array['picLink'], $arg_array['startDate'], $arg_array['endDate'], $arg_array['link'], $arg_array['description'], $arg_array['summary'] )) {
            return array( 'code'=>400 , 'message'=>'参数错误');
        }
        if (!is_numeric($arg_array['menuID'])) {
            return array( 'code'=>400 , 'message'=>'参数错误');
        }

        if (empty($arg_array['title'])) {
            return array( 'code'=>400 , 'message'=>'标题不能为空');
        }
        if (empty($arg_array['picLink'])) {
            return array( 'code'=>400 , 'message'=>'请上传图片');
        }
        if (!$commHandler->isDate($arg_array['startDate'])) {
            return array( 'code'=>400 , 'message'=>'开始时间不能为空');
        }
        if (!$commHandler->isDate($arg_array['endDate'])) {
            return array( 'code'=>400 , 'message'=>'结束时间不能为空');
        }
        if ($arg_array['startDate'] > $arg_array['endDate']) {
            return array( 'code'=>400 , 'message'=>'开始时间不能大于结束时间');
        }

        if ( !empty($arg_array['link']) ) {
            $arg_array['description'] = null;
        } else {
            if (empty($arg_array['description'])) {
                return array( 'code'=>400 , 'message'=>'正文内容不能为空');
            }
            $arg_array['link'] = null;
        }

        if (!isset($arg_array['mapID']) || !is_numeric($arg_array['mapID']) || $arg_array['mapID'] <= 0) {
            $arg_array['mapID'] = 0;
        }

        if (!isset($arg_array['materialID']) || !is_numeric($arg_array['materialID']) || $arg_array['materialID'] <= 0) {
            $arg_array['materialID'] = 0;
        }

        try {

            //查询菜单信息
            $temp_array = array(
                'menuID' => $arg_array['menuID']
            );
            $menu_array = $this->searchMenuList( $temp_array );
            if (!$menu_array) {
                throw new Exception('菜单信息没有找到', 404);
            }

            //保存(更新)菜单映射
            $wechat_menu_material_map = new entity('wechat_menu_material_map');
            $wechat_menu_material_map->menuID = $arg_array['menuID'];
            if( $arg_array['mapID'] > 0 ){

                $wechat_menu_material_map->mapID = $arg_array['mapID'];
                if (!$this->dbca->fetch($wechat_menu_material_map)) {
                    throw new Exception('回复内容信息没有找到', 404);
                }

            } else {

                //实例化公共类
                $commHandler = new commHandler($this->dbca);

                //获取映射ID自增量
                $arg_array['mapID'] = $commHandler->generate_seqno('seqno_wechatmap');

                $wechat_menu_material_map->mapID = $arg_array['mapID'];

                $wechat_menu_material_map->creator = $arg_array['operator'];
            }

            //检查排期是否冲突
            $temp_array['mapID'] = $arg_array['mapID'];
            $temp_array['startDate'] = $arg_array['startDate'];
            $temp_array['endDate'] = $arg_array['endDate'];
            $checkResult = $this->checkMenuRepeatDate( $temp_array );
            if ( $checkResult['code'] == 200 && $checkResult['data'] == 1 ) {
                throw new Exception('当前时间段已有其他回复内容', 404);
            }

            //如果链接为空，则保存/更新cms内容
            if ( empty($arg_array['link']) && $arg_array['selectedFlg'] == 0 ) {

                $temp_array = array(
                    'creator' => $arg_array['operator'],
                    'article_id' => $arg_array['cmsID'],
                    'article_title' => $arg_array['title'],
                    'code_type' => $arg_array['code_type'],
                    'activeType' => $arg_array['activeType'],
                    'code_startDate' => $arg_array['code_startDate'],
                    'code_endDate' => $arg_array['code_endDate'],
                    'use_startDate' => $arg_array['use_startDate'],
                    'use_endDate' => $arg_array['use_endDate'],
                    'limit_num' => $arg_array['limit_num'],
                    'useType' => $arg_array['useType'],
                    'useTime' => $arg_array['useTime'],
                    'article_summary' => $arg_array['summary'],
                    'description' => $arg_array['description'],
                    'promotionID' => $arg_array['promotionID'],
                    'category_id' => 6
                );
                $article_array = $this->saveArticleInfo( $temp_array );
                if ($article_array['code'] != 200) {
                    throw new Exception($article_array['message'], 404);
                }
                $arg_array['article_id'] = $article_array['data'];
            }

            //页面“选择”模板
            if( $arg_array['cmsID'] > 0 &&  $arg_array['selectedFlg'] == 1){
                $arg_array['article_id'] = $arg_array['cmsID'];
            }

            //存在链接时，清空模板ID
            if( !empty( $arg_array['link'] ) || ( empty($arg_array['cmsID']) && !isset($arg_array['article_id']) ) ){
                $arg_array['article_id'] = NULL;
            }

            //保存(更新)素材
            $wechat_material = new entity('wechat_material');
            if( $arg_array['materialID'] > 0 ){

                $wechat_material->materialID = $arg_array['materialID'];
                if (!$this->dbca->fetch($wechat_material)) {
                    throw new Exception('回复内容信息没有找到', 404);
                }

            } else {
                $wechat_material->creator = $arg_array['operator'];
            }

            //将图片路径打成数组
            $picture_array = explode( '/' , $arg_array['picLink'] );

            //转移图片路径
            if( $picture_array[0] == '' || $picture_array[1] == 'quanliadmin' ){

                if( ($arg_array['mapID'] &&  $arg_array['picLink'] != $wechat_material->picLink) || empty($arg_array['mapID']) ){

                    $oldName = G_APPLICATION_BASEPATH . $arg_array['picLink'];
                    $newName = G_IMAGE_SAVE_ROOT . 'wechat/cotent/' . $fileDirHandler->basename($oldName);

                    if (!$fileDirHandler->move($oldName, $newName)) {
                        throw new Exception('文件移动失败', 404);
                    }

                    $arg_array['picLink'] = 'wechat/cotent/' . $fileDirHandler->basename($oldName);

                }

            }

            $wechat_material->materialType = $arg_array['menuType'];
            $wechat_material->materialTitle = $arg_array['title'];
            $wechat_material->link = $arg_array['link'];
            $wechat_material->picLink = $arg_array['picLink'];
            $wechat_material->description = $arg_array['summary'];
            $wechat_material->article_id = $arg_array['article_id'];
            $this->dbca->save($wechat_material);

            if( $arg_array['materialID'] == 0 ){
                $arg_array['materialID'] = $this->dbca->insert_id;
            }

            //保存(更新)映射表信息
            $wechat_menu_material_map->materialID = $arg_array['materialID'];
            $wechat_menu_material_map->startDate = $arg_array['startDate'];
            $wechat_menu_material_map->endDate = $arg_array['endDate'];

            //保存映射表信息
            $this->dbca->save( $wechat_menu_material_map );

            return array( 'code'=> 200 , 'message' => '保存成功', 'data' => $arg_array['mapID'] );


        } catch (Exception $e){

            if( $e->getCode() > 0 ){

                return array( 'code'=>$e->getCode() , 'message'=>$e->getMessage() );

            } else {

                error_log( $e->getMessage() );
                return array( 'code'=>500 , 'message'=>$e->getMessage() );

            }

        }

    }

    /**
     * 保存菜单文本回复
     */
    public function saveMenuTextReply( $arg_array ){

        if( !isset( $arg_array['menuID'], $arg_array['content'],  $arg_array['startDate'], $arg_array['endDate'], $arg_array['link'], $arg_array['description'], $arg_array['summary'] )) {
            return array( 'code'=>400 , 'message'=>'参数错误');
        }

        if( !is_numeric( $arg_array['menuID'] ) ){
            return array( 'code'=>400 , 'message'=>'参数错误');
        }

        if( empty( $arg_array['content'] ) ){
            return array( 'code'=>400 , 'message'=>'请输入文本内容');
        }

        if( empty( $arg_array['startDate'] ) ){
            return array( 'code'=>400 , 'message'=>'开始时间不能为空');
        }

        if( empty( $arg_array['endDate'] ) ){
            return array( 'code'=>400 , 'message'=>'结束时间不能为空');
        }

        if( $arg_array['startDate'] > $arg_array['endDate'] ){
            return array( 'code'=>400 , 'message'=>'开始时间不能大于结束时间');
        }

        if( !empty($arg_array['link']) ){

            $arg_array['description'] = NULL;

        } else {

            if( !empty($arg_array['description']) ){

                if( empty( $arg_array['title'] ) ){
                    return array( 'code'=>400 , 'message'=>'标题不能为空');
                }

                $arg_array['link'] = NULL;

            }

        }

        if (!isset($arg_array['mapID']) || !is_numeric($arg_array['mapID']) || $arg_array['mapID'] <= 0) {
            $arg_array['mapID'] = 0;
        }

        if (!isset($arg_array['materialID']) || !is_numeric($arg_array['materialID']) || $arg_array['materialID'] <= 0) {
            $arg_array['materialID'] = 0;
        }

        try{

            //查询菜单信息
            $temp_array = array(
                'menuID' => $arg_array['menuID']
            );
            $menu_array = $this->searchMenuList( $temp_array );
            if (!$menu_array) {
                throw new Exception('菜单信息没有找到', 404);
            }

            //保存(更新)菜单映射
            $wechat_menu_material_map = new entity('wechat_menu_material_map');
            $wechat_menu_material_map->menuID = $arg_array['menuID'];
            if( $arg_array['mapID'] > 0 ){

                $wechat_menu_material_map->mapID = $arg_array['mapID'];
                if (!$this->dbca->fetch($wechat_menu_material_map)) {
                    throw new Exception('回复内容信息没有找到', 404);
                }

            } else {

                //实例化公共类
                $commHandler = new commHandler($this->dbca);

                //获取映射ID自增量
                $arg_array['mapID'] = $commHandler->generate_seqno('seqno_wechatmap');

                $wechat_menu_material_map->mapID = $arg_array['mapID'];

                $wechat_menu_material_map->creator = $arg_array['operator'];
            }

            //检查排期是否冲突
            $temp_array['mapID'] = $arg_array['mapID'];
            $temp_array['startDate'] = $arg_array['startDate'];
            $temp_array['endDate'] = $arg_array['endDate'];
            $checkResult = $this->checkMenuRepeatDate( $temp_array );
            if ( $checkResult['code'] == 200 && $checkResult['data'] == 1 ) {
                throw new Exception('当前时间段已有其他回复内容', 404);
            }

            //如果链接为空,正文不为空,则保存CMS
            if( empty($arg_array['link']) && !empty( $arg_array['description'] ) && $arg_array['selectedFlg'] == 0 ){

                $temp_array = array(
                    'creator' => $arg_array['operator'],
                    'article_id' => $arg_array['cmsID'],
                    'article_title' => $arg_array['title'],
                    'code_type' => $arg_array['code_type'],
                    'activeType' => $arg_array['activeType'],
                    'code_startDate' => $arg_array['code_startDate'],
                    'code_endDate' => $arg_array['code_endDate'],
                    'use_startDate' => $arg_array['use_startDate'],
                    'use_endDate' => $arg_array['use_endDate'],
                    'limit_num' => $arg_array['limit_num'],
                    'useType' => $arg_array['useType'],
                    'useTime' => $arg_array['useTime'],
                    'article_summary' => $arg_array['summary'],
                    'description' => $arg_array['description'],
                    'promotionID' => $arg_array['promotionID'],
                    'category_id' => 6
                );

                $article_array = $this->saveArticleInfo( $temp_array );
                if ($article_array['code'] != 200) {
                    throw new Exception($article_array['message'], 404);
                }
                $arg_array['article_id'] = $article_array['data'];

            }

            //页面“选择”模板
            if( $arg_array['cmsID'] > 0 &&  $arg_array['selectedFlg'] == 1){
                $arg_array['article_id'] = $arg_array['cmsID'];
            }

            //存在链接时，清空模板ID
            if( !empty( $arg_array['link'] ) || ( empty($arg_array['cmsID']) && !isset($arg_array['article_id']) ) ){
                $arg_array['article_id'] = NULL;
            }

            //保存(更新)素材
            $wechat_material = new entity('wechat_material');
            if( $arg_array['materialID'] > 0 ){

                $wechat_material->materialID = $arg_array['materialID'];
                if (!$this->dbca->fetch($wechat_material)) {
                    throw new Exception('回复内容信息没有找到', 404);
                }

            } else {
                $wechat_material->creator = $arg_array['operator'];
            }

            $wechat_material->materialType = $arg_array['menuType'];
            $wechat_material->materialTitle = $arg_array['title'];
            $wechat_material->description = $arg_array['content'];
            $wechat_material->link = $arg_array['link'];
            $wechat_material->article_id = $arg_array['article_id'];
            $this->dbca->save($wechat_material);

            if( $arg_array['materialID'] == 0 ){
                $arg_array['materialID'] = $this->dbca->insert_id;
            }

            //保存(更新)映射表信息
            $wechat_menu_material_map->materialID = $arg_array['materialID'];
            $wechat_menu_material_map->startDate = $arg_array['startDate'];
            $wechat_menu_material_map->endDate = $arg_array['endDate'];

            //保存映射表信息
            $this->dbca->save( $wechat_menu_material_map );

            return array( 'code'=> 200 , 'message' => '保存成功', 'data' => $arg_array['mapID'] );

        }catch ( Exception $e ){

            if( $e->getCode() > 0 ){

                return array( 'code'=>$e->getCode() , 'message'=>$e->getMessage() );

            } else {

                error_log( $e->getMessage() );
                return array( 'code'=>500 , 'message'=>$e->getMessage() );

            }

        }

    }

    /**
     * 删除菜单事件排期
     */
    public function deleteMenuMap( $arg_array ){

        if( !isset( $arg_array['menuID'] , $arg_array['mapID']) || !is_numeric($arg_array['menuID']) || !is_numeric($arg_array['mapID']) ){
            return array( 'code'=>400 , 'message'=>'参数错误' );
        }

        try{

            //查询菜单排期信息
            $map_obj = new entity('wechat_menu_material_map');
            $map_obj->mapID = $arg_array['mapID'];
            $map_obj->menuID = $arg_array['menuID'];

            if( !$this->dbca->fetch( $map_obj ) ){
                throw new Exception( '排期回复信息没找到' , 404 );
            }

            //删除
            $this->dbca->delete( $map_obj );

            return array( 'code'=>200 , 'message'=>'删除成功' , 'data'=>$arg_array['mapID'] );

        }catch (Exception $e){

            if( $e->getCode() > 0 ){

                return array( 'code'=>$e->getCode() , 'message'=>$e->getMessage() );

            } else {

                error_log( $e->getMessage() );
                return array( 'code'=>500 , 'message'=>$e->getMessage() );

            }

        }

    }

    /**
     * 查询投票信息
     * @param array $arg_array 查询参数数组
     * $arg_array = array (
     *      'sortname' => string 排序字段
     *      'sortorder' => string 排序方式
     *      'page' => int 分页页码
     *      'rp' => int 分页页数
     * )
     * @return null
     */
    public function searchVoteInfo( &$arg_array ) {

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //投票信息ID
        if ( isset($arg_array['voteID']) && is_numeric($arg_array['voteID']) ) {
            $sql .= ' AND voteID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['voteID'];
        }

        //投票标题
        if ( isset($arg_array['voteTitle']) && !empty($arg_array['voteTitle']) ) {
            $sql .= ' AND voteTitle = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['voteTitle'];
        }

        //投票信息审核状态
        if ( isset($arg_array['voteStatus']) && is_numeric($arg_array['voteStatus']) ) {
            $sql .= ' AND voteStatus = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['voteStatus'];
        }

        //使用状态
        if ( isset($arg_array['useFlg']) && is_numeric($arg_array['useFlg']) ) {
            $sql .= ' AND useFlg = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['useFlg'];
        }

        //日期

        if ( isset($arg_array['nowDate']) && !empty($arg_array['nowDate']) ) {
            $sql .= ' AND endDate >= ?';
            $params_type .= 's';
            $params_array[] = $arg_array['nowDate'];
        }

        if ( $sql ) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if ( isset($arg_array['rp']) && $arg_array['rp'] > 1 ) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM wechat_vote ' . $sql;

                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if ( isset($arg_array['sortname']) && !empty($arg_array['sortname']) )
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if ( !isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0 )
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if ( isset($arg_array['sortname']) && !empty($arg_array['sortname']) )
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询分类信息
            $search_sql = 'SELECT * FROM wechat_vote ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            foreach($temp_item_array as &$item) {

                $item_array[] = array(
                    'voteID' 	  => $item->voteID,
                    'voteTitle' 	  => $item->voteTitle,
                    'startDate' 	  => $item->startDate,
                    'endDate' 	  => $item->endDate,
                    'voteNum' 	  => $item->voteNum,
                    'voteStatus' 	  => $item->voteStatus,
                    'useFlg' 	  => $item->useFlg
                );
            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }

    /**
     * 查询投票主题信息
     * @param array $arg_array 查询参数数组
     * $arg_array = array (
     *      'sortname' => string 排序字段
     *      'sortorder' => string 排序方式
     *      'page' => int 分页页码
     *      'rp' => int 分页页数
     * )
     * @return null
     */
    public function searchVoteTheme( &$arg_array ) {

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //投票信息ID
        if ( isset($arg_array['voteID']) && is_numeric($arg_array['voteID']) ) {
            $sql .= ' AND voteID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['voteID'];
        }

        //投票主题ID
        if ( isset($arg_array['themeID']) && is_numeric($arg_array['themeID']) ) {
            $sql .= ' AND themeID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['themeID'];
        }

        //投票标题
        if ( isset($arg_array['themeName']) && !empty($arg_array['themeName']) ) {
            $sql .= ' AND themeName = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['themeName'];
        }

        if ( $sql ) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if ( isset($arg_array['rp']) && $arg_array['rp'] > 1 ) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM wechat_vote_theme ' . $sql;

                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if ( isset($arg_array['sortname']) && !empty($arg_array['sortname']) )
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if ( !isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0 )
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if ( isset($arg_array['sortname']) && !empty($arg_array['sortname']) )
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询分类信息
            $search_sql = 'SELECT * FROM wechat_vote_theme ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            foreach($temp_item_array as &$item) {

                $item_array[] = array(
                    'voteID' 	  => $item->voteID,
                    'themeID' 	  => $item->themeID,
                    'themeName' 	  => $item->themeName,
                    'canMulti' 	  => $item->canMulti,
                    'isMust' 	  => $item->isMust,
                    'themeNum' 	  => $item->themeNum
                );
            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }

    /**
     * 查询投票主题选项信息
     * @param array $arg_array 查询参数数组
     * $arg_array = array (
     *      'sortname' => string 排序字段
     *      'sortorder' => string 排序方式
     *      'page' => int 分页页码
     *      'rp' => int 分页页数
     * )
     * @return null
     */
    public function searchVoteThemeOption( &$arg_array ) {

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //投票信息ID
        if ( isset($arg_array['voteID']) && is_numeric($arg_array['voteID']) ) {
            $sql .= ' AND voteID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['voteID'];
        }

        //投票主题ID
        if ( isset($arg_array['themeID']) && is_numeric($arg_array['themeID']) ) {
            $sql .= ' AND themeID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['themeID'];
        }

        //投票选项名称
        if ( isset($arg_array['optionName']) && !empty($arg_array['optionName']) ) {
            $sql .= ' AND optionName = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['optionName'];
        }

        if ( $sql ) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if ( isset($arg_array['rp']) && $arg_array['rp'] > 1 ) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM wechat_vote_theme_option ' . $sql;

                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if ( isset($arg_array['sortname']) && !empty($arg_array['sortname']) )
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if ( !isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0 )
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if ( isset($arg_array['sortname']) && !empty($arg_array['sortname']) )
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询分类信息
            $search_sql = 'SELECT * FROM wechat_vote_theme_option ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            foreach($temp_item_array as &$item) {

                $item_array[] = array(
                    'voteID' 	  => $item->voteID,
                    'themeID' 	  => $item->themeID,
                    'optionID' 	  => $item->optionID,
                    'optionName' 	  => $item->optionName,
                    'optionNum' 	  => $item->optionNum,
                    'optionSortby' 	  => $item->optionSortby,
                    'optionImg' 	  => $item->optionImg
                );
            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }

    /**
     * 查询会员提交的投票选项详情
     * @param array $arg_array 查询参数数组
     * $arg_array = array (
     *      'sortname' => string 排序字段
     *      'sortorder' => string 排序方式
     *      'page' => int 分页页码
     *      'rp' => int 分页页数
     * )
     * @return null
     */
    public function searchVoteCustDetail( &$arg_array ) {

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //投票信息ID
        if ( isset($arg_array['voteID']) && is_numeric($arg_array['voteID']) ) {
            $sql .= ' AND voteID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['voteID'];
        }

        //投票选项名称
        if ( isset($arg_array['optionName']) && !empty($arg_array['optionName']) ) {
            $sql .= ' AND optionName = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['optionName'];
        }

        if (isset($arg_array['extend']) && !empty($arg_array['extend'])) {
            $sql .= $arg_array['extend'];
        }

        if ( $sql ) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if ( isset($arg_array['rp']) && $arg_array['rp'] > 1 ) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM wechat_vote_cust_detail ' . $sql;

                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if ( isset($arg_array['sortname']) && !empty($arg_array['sortname']) )
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if ( !isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0 )
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if ( isset($arg_array['sortname']) && !empty($arg_array['sortname']) )
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询分类信息
            $search_sql = 'SELECT * FROM wechat_vote_cust_detail ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            foreach($temp_item_array as &$item) {

                $item_array[] = array(
                    'qcID' 	  => $item->qcID,
                    'voteID' 	  => $item->voteID,
                    'themeID' 	  => $item->themeID,
                    'optionID' 	  => $item->optionID,
                    'optionName' 	  => $item->optionName
                );
            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }

    /**
     * 查询投票统计结果
     * @author raohenglei
     */
    public function searchVoteResult( &$arg_array ){

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //投票信息ID
        if ( isset($arg_array['voteID']) && is_numeric($arg_array['voteID']) ) {
            $sql .= ' AND voteID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['voteID'];
        }

        //投票主题ID
        if ( isset($arg_array['themeID']) && is_numeric($arg_array['themeID']) ) {
            $sql .= ' AND themeID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['themeID'];
        }

        if ( $sql ) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            //查询投票统计信息
            $search_sql = 'SELECT voteID,themeID,optionID,COUNT(optionID) as count FROM wechat_vote_cust_detail ' . $sql .' GROUP BY voteID,themeID,optionID';
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            foreach($temp_item_array as &$item) {

                $item_array[] = array(
                    'voteID' 	  => $item->voteID,
                    'themeID' 	  => $item->themeID,
                    'optionID' 	  => $item->optionID,
                    'count' 	  => $item->count
                );
            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }

    /**
     * 查询活动模板
     * @param array $arg_array 查询参数数组
     * $arg_array = array (
     *      'sortname' => string 排序字段
     *      'sortorder' => string 排序方式
     *      'page' => int 分页页码
     *      'rp' => int 分页页数
     * )
     * @return null
     */
    public function searchActivityTemplet( &$arg_array ) {

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //活动模板ID
        if ( isset($arg_array['templetID']) && is_numeric($arg_array['templetID']) ) {
            $sql .= ' AND templetID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['templetID'];
        }

        //活动模板名称
        if ( isset($arg_array['templetName']) && !empty($arg_array['templetName']) ) {
            $sql .= ' AND templetName = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['templetName'];
        }

        //是否生码
        if ( isset($arg_array['isCode']) && in_array( $arg_array['isCode'] , array(0,1) ) ) {
            $sql .= ' AND isCode = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['isCode'];
        }

        if ( $sql ) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if ( isset($arg_array['rp']) && $arg_array['rp'] > 1 ) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM wechat_activity_templet ' . $sql;

                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if ( isset($arg_array['sortname']) && !empty($arg_array['sortname']) )
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if ( !isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0 )
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if ( isset($arg_array['sortname']) && !empty($arg_array['sortname']) )
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询分类信息
            $search_sql = 'SELECT * FROM wechat_activity_templet ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            foreach($temp_item_array as &$item) {
                $item_array[] = array(
                    'templetID' 	  => $item->templetID,
                    'templetName' 	  => $item->templetName,
                    'logo' 	          => $item->logo,
                    'description' 	  => $item->description,
                    'isCode' 	      => $item->isCode,
                    'external_no' 	  => $item->external_no,
                    'interfaceClass'=> $item->interfaceClass
                );
            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }

    /**
     * 查询关键词别名信息
     * @param array $arg_array 查询参数数组
     * $arg_array = array (
     *      'sortname' => string 排序字段
     *      'sortorder' => string 排序方式
     *      'page' => int 分页页码
     *      'rp' => int 分页页数
     * )
     * @return null
     */
    public function searchKeywordsAlias( &$arg_array ) {

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //主关键词ID
        if ( isset($arg_array['mainKeyWordsID']) && is_numeric($arg_array['mainKeyWordsID']) ) {
            $sql .= ' AND mainKeyWordsID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['mainKeyWordsID'];
        }

        //关键词别名
        if ( isset($arg_array['aliasName']) && !empty($arg_array['aliasName']) ) {
            $sql .= ' AND aliasName = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['aliasName'];
        }

        //是否是主关键词
        if ( isset($arg_array['isMain']) && in_array( $arg_array['isMain'] , array(0,1) ) ) {
            $sql .= ' AND isMain = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['isMain'];
        }

        if ( $sql ) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if ( isset($arg_array['rp']) && $arg_array['rp'] > 1 ) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count
                            FROM wechat_keywords_alias wka INNER JOIN wechat_keywords wk
                            ON wka.mainKeyWordsID = wk.keyID ' . $sql;

                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if ( isset($arg_array['sortname']) && !empty($arg_array['sortname']) )
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if ( !isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0 )
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if ( isset($arg_array['sortname']) && !empty($arg_array['sortname']) )
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询分类信息
            $search_sql = 'SELECT wka.aliasID,wka.aliasName,wka.isMain,
                        wk.keyID,wk.keyword,wk.description,wk.parentID,wk.level,wk.useFlg
                        FROM wechat_keywords_alias wka INNER JOIN wechat_keywords wk
                        ON wka.mainKeyWordsID = wk.keyID ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            foreach($temp_item_array as &$item) {
                $item_array[] = array(
                    'aliasID' => $item->aliasID,
                    'aliasName' => $item->aliasName,
                    'isMain' => $item->isMain,
                    'keyword' 	  => $item->keyword,
                    'description' 	=> $item->description,
                    'parentID'=> $item->parentID,
                    'level'=> $item->level,
                    'useFlg'=> $item->useFlg
                );
            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }


    /**
     * 查询多图文映射表信息
     * @param array $arg_array 查询参数数组
     * $arg_array = array (
     *      'sortname' => string 排序字段
     *      'sortorder' => string 排序方式
     *      'page' => int 分页页码
     *      'rp' => int 分页页数
     * )
     * @return null
     */
    public function searchNewsMap( &$arg_array ){

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //排期ID
        if ( isset($arg_array['mapID']) && is_numeric($arg_array['mapID']) ) {
            $sql .= ' AND wnm.mapID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['mapID'];
        }

        //素材ID
        if ( isset($arg_array['materialID']) &&  is_numeric($arg_array['materialID']) ) {
            $sql .= ' AND materialID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['materialID'];
        }

        if( isset( $arg_array['extendSql'] ) && !empty( $arg_array['extendSql'] ) ){
            $sql .= $arg_array['extendSql'];
        }

        if ( $sql ) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if ( isset($arg_array['rp']) && $arg_array['rp'] > 1 ) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count
                            FROM wechat_news_map wnm
                            INNER JOIN wechat_material wm
                            ON wnm.materialID = wm.materialID ' . $sql;

                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }


                $arg_array['count'] = $item_count;

                //排序
                if ( isset($arg_array['sortname']) && !empty($arg_array['sortname']) )
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if ( !isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0 )
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if ( isset($arg_array['sortname']) && !empty($arg_array['sortname']) )
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询分类信息
            $search_sql = 'SELECT wm.*,wnm.mapID,wnm.sortOrder
                        FROM wechat_news_map wnm
                        INNER JOIN wechat_material wm
                        ON wnm.materialID = wm.materialID ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            foreach($temp_item_array as &$item) {
                $item_array[] = array(
                    'mapID' 	      => $item->mapID,
                    'sortOrder' 	  => $item->sortOrder,
                    'materialID' 	  => $item->materialID,
                    'materialType'  => $item->materialType,
                    'materialTitle' => $item->materialTitle,
                    'picLinkShow' => empty($item->picLink) ? '' : G_IMAGE_URL.$item->picLink,
                    'picLink' 	      => $item->picLink,
                    'description' 	  => $item->description,
                    'link' 	          => $item->link,
                    'article_id' 	  => $item->article_id
                );
            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }

    /**
     * 保存素材
     */
    public function saveMeterialInfo( $arg_array ){

        if( !isset( $arg_array['materialType'] ) || !is_numeric($arg_array['materialType']) || !in_array( $arg_array['materialType'] , array(1,2,3) ) ){
            return array( 'code'=>400 , 'message'=>'参数错误' );
        }

        if( !isset($arg_array['materialID']) || $arg_array['materialID'] == 0 || !is_numeric($arg_array['materialID']) ){
            $arg_array['materialID'] = 0;
        }

        try{

            //开启事务
            $this->dbca->beginTransaction();

            quanli_include('module/base/fileDirHandler.class.php');

            //实例化类
            $fileDirHandler = new fileDirHandler();

            //保存(更新)素材
            $wechat_material = new entity('wechat_material');
            if( $arg_array['materialID'] > 0 ){

                $wechat_material->materialID = $arg_array['materialID'];
                if (!$this->dbca->fetch($wechat_material)) {
                    throw new Exception('回复内容信息没有找到', 404);
                }

            } else {
                $wechat_material->creator = $arg_array['operator'];
            }

            //如果链接为空且“选择模板标志”为“否”
            if ( empty($arg_array['link']) && $arg_array['selectedFlg'] == 0 ) {

                $temp_array = array(
                    'creator' => $arg_array['operator'],
                    'article_id' => isset($arg_array['cmsID'])?$arg_array['cmsID']:'',
                    'article_title' => $arg_array['title'],
                    'code_type' => $arg_array['code_type'],
                    'activeType' => $arg_array['activeType'],
                    'code_startDate' => isset($arg_array['code_startDate'])?$arg_array['code_startDate']:'',
                    'code_endDate' => isset($arg_array['code_endDate'])?$arg_array['code_endDate']:'',
                    'use_startDate' => isset($arg_array['use_startDate'])?$arg_array['use_startDate']:'',
                    'use_endDate' => isset($arg_array['use_endDate'])?$arg_array['use_endDate']:'',
                    'limit_num' => isset($arg_array['limit_num'])?$arg_array['limit_num']:0,
                    'useType' => isset($arg_array['useType'])?$arg_array['useType']:1,
                    'useTime' => isset($arg_array['useTime'])?$arg_array['useTime']:'',
                    'article_summary' => isset($arg_array['summary'])?$arg_array['summary']:'',
                    'description' => isset($arg_array['description'])?$arg_array['description']:'',
                    'promotionID' => isset($arg_array['promotionID'])?$arg_array['promotionID']:'',
                    'category_id' => 6
                );

                //如果正文不为空，则保存或更新模板信息
                if( !empty($temp_array['description']) ){

                    if( empty($arg_array['title']) ){
                        throw new Exception('标题不能为空' , 400);
                    }

                    $article_array = $this->saveArticleInfo( $temp_array );
                    if ($article_array['code'] != 200) {
                        throw new Exception($article_array['message'], 404);
                    }
                    $arg_array['article_id'] = $article_array['data'];
                }

            }

            //页面“选择”模板
            if( $arg_array['cmsID'] > 0 &&  $arg_array['selectedFlg'] == 1){
                $arg_array['article_id'] = $arg_array['cmsID'];
            }

            //存在链接时，清空模板ID
            if( !empty( $arg_array['link'] ) || ( empty($arg_array['cmsID']) && !isset($arg_array['article_id']) ) ){
                $arg_array['article_id'] = NULL;
            }

            //图片处理
            if( !empty($arg_array['picLink']) ){

                //将图片路径打成数组
                $picture_array = explode( '/' , $arg_array['picLink'] );

                //转移图片路径
                if( $picture_array[0] == '' || $picture_array[1] == 'quanliadmin' ){

                    $oldName = G_APPLICATION_BASEPATH . $arg_array['picLink'];
                    $newName = G_IMAGE_SAVE_ROOT . 'wechat/cotent/' . $fileDirHandler->basename($oldName);

                    if (!$fileDirHandler->move($oldName, $newName)) {
                        throw new Exception('文件移动失败', 404);
                    }

                    $arg_array['picLink'] = 'wechat/cotent/' . $fileDirHandler->basename($oldName);

                }

            }

            $wechat_material->materialType = $arg_array['materialType'];
            $wechat_material->materialTitle = isset($arg_array['title'])?$arg_array['title']:'';
            $wechat_material->link = isset($arg_array['link'])?$arg_array['link']:'';
            $wechat_material->picLink = isset($arg_array['picLink'])?$arg_array['picLink']:'';
            $wechat_material->description = isset($arg_array['summary'])?$arg_array['summary']:'';
            $wechat_material->article_id = $arg_array['article_id'];
            $this->dbca->save($wechat_material);

            if( $arg_array['materialID'] == 0 ){
                $arg_array['materialID'] = $this->dbca->insert_id;
            }

            //提交事务
            $this->dbca->commit();

            return array( 'code'=>200 , 'message'=>'保存成功' , 'data'=>$arg_array['materialID'] , 'article_id'=>$arg_array['article_id'] );

        }catch (Exception $e){

            //回滚事务
            $this->dbca->rollBack();

            if( $e->getCode() > 0 ){
                return array( 'code'=>$e->getCode() , 'message'=>$e->getMessage() );
            } else {
                error_log( $e->getMessage() );
                return array( 'code'=>500 , 'message'=>'系统错误，保存失败' );
            }

        }

    }


    /**
     * 客服设置内容列表
     */
    function searchServiceReply( $arg_array ){

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //内容ID
        if ( isset($arg_array['mapID']) && is_numeric($arg_array['mapID']) ) {
            $sql .= ' AND wcm.mapID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['mapID'];
        }

        //有效期开始日期
        if ( isset($arg_array['startDate']) && !empty($arg_array['startDate']) ) {
            $sql .= ' AND wcm.startTime <= ?';
            $params_type .= 's';
            $params_array[] = $arg_array['startDate'];
        }

        //有效期结束日期
        if ( isset($arg_array['endDate']) && !empty($arg_array['endDate']) ) {
            $sql .= ' AND wcm.endTime >= ?';
            $params_type .= 's';
            $params_array[] = $arg_array['endDate'];
        }

        //是否是多图文
        if ( isset($arg_array['isHost']) && in_array( $arg_array['isHost'] , array(0,1) ) ) {
            $sql .= ' AND wcm.isHost = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['isHost'];
        }

        if( !empty( $arg_array['extendSql'] ) ){
            $sql .= $arg_array['extendSql'];
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count
                            FROM wechat_customerService_map wcm
                            INNER JOIN wechat_material wm ON wcm.materialID = wm.materialID ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询信息
            $search_sql = 'SELECT wcm.mapID,wcm.startTime,wcm.endTime,wcm.isHost,
                        wcm.materialID,wm.materialType,wm.materialTitle,wm.picLink,wm.description,wm.link,wm.article_id,wm.timeStamp,wm.createTime,
                        wm.media_id,wm.media_time
                        FROM wechat_customerService_map wcm
                        INNER JOIN wechat_material wm ON wcm.materialID = wm.materialID ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            foreach($temp_item_array as &$item) {
                $item_array[] = array(
                    'timeStamp'  => $item->timeStamp,
                    'createTime'  => $item->createTime,
                    'mapID'  => $item->mapID,
                    'startDate' => $item->startTime,
                    'endDate' => $item->endTime,
                    'startTime' => date('Y-m-d' , strtotime($item->startTime)),
                    'endTime' => date('Y-m-d' , strtotime($item->endTime)),
                    'isHost' => $item->isHost,
                    'materialID' => $item->materialID,
                    'materialType' => $item->materialType,
                    'materialTitle' => $item->materialTitle,
                    'picLinkShow' => empty($item->picLink) ? '' : G_IMAGE_URL.$item->picLink,
                    'picLink' => $item->picLink,
                    'description' => $item->description,
                    'link' => $item->link,
                    'article_id' => $item->article_id,
                    'media_id' => $item->media_id,
                    'media_time' => $item->media_time
                );

            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;


        }

    }


}